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 (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...