如何解决Angular 服务在运行构造函数之前不等待 APP_INITIALIZER 完成
在我的 angular 应用程序中,我想在运行应用程序之前从 firestore 集合中读取配置。我写了这段代码来做到这一点:
@Injectable()
export class ConfigService {
private _config: Config;
public get config(): Config {
return this._config;
}
constructor(private readonly firestore: AngularFirestore) {}
loadConfig(): Promise<boolean> {
return new Promise((resolve) => {
this.firestore
.collection('config')
.doc<Config>(environment.configId)
.get()
.subscribe((snap) => {
this._config = snap.data();
resolve(true);
});
});
}
}
// app.module.ts
export const ConfigureApp = {
provide: APP_INITIALIZER,useFactory: (config: ConfigService) => () => config.loadConfig(),deps: [ConfigService],multi: true,};
@NgModule({
declarations: [AppComponent],imports: [CoreModule,...],providers: [ConfigureApp],bootstrap: [AppComponent],})
我有多个服务读取其配置,只需在构造函数中注入 ConfigService
并访问 getter config
。
它适用于所有人,但不适用于一个:
@Injectable()
export class SlackService {
private readonly HOOK_URL: string;
constructor(private readonly api: ApiService,private readonly configService: ConfigService) {
this.HOOK_URL = this.configService.config.slackHookUrl;
}
async send(content: any): Promise<void> {
const message: SlackMessage = { timestamp: moment.Now(),type: 'error',content };
const payload: SlackPayload = { channel: 'channel',text: JSON.stringify(message) };
const headers: HttpHeaders = new HttpHeaders();
headers = headers.set('Content-type','application/x-www-form-urlencoded');
await this.api.post<void>(this.HOOK_URL,payload,{ headers });
}
}
这是我添加的最后一个,我看不出与其他的有什么不同。所有服务都添加到 providers
中的 CoreModule
数组中,CoreModule
导入到 AppModule
中。
加载时使用的其他服务等待应用初始化,然后正确发出 http 请求。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。