首页 > 解决方案 > 库中的 APP_INITIALIZER 函数

问题描述

最近,我发现自己为我正在制作的每个 Angular 应用程序都在 AppLoadingModule 中编写了相同的 init_app 方法。所以我决定编写一个包含我项目之间所有常见内容的库。我想将这个 init_app 函数移到 lib 中。

我可以更好地解释一下:我的库中有一个服务,它从资产文件夹加载配置文件。目前,在我的 Angular 应用程序的 app-loading.module.ts 中,我有以下代码:

@NgModule({
  imports: [],
  providers: [
    { provide: APP_INITIALIZER, useFactory: init_app, multi: true, deps: [
      ConfigurationService,
      HttpClient
    ]}
  ]
})
export class AppLoadingModule {}

export function init_app(
  configurationService: ConfigurationService,
  http: HttpClient
): () => Promise<any> {
  return (): Promise<any> => {
    return new Promise((resolve, reject) => {
      const env = environment.production ? 'production' : 'development';
      console.log(`init_app:: ${env}`);
      Promise.all([
        configurationService.loadConfiguration(http, env)
      ])
      .then(() => {
        resolve();
      })
      .catch((err) => {
        console.log(`Error fetching configuration: ${err}`);
        // Try continue
        resolve();
      });
    });
  };
}

有没有办法从库中移动或调用这个函数?我试图将整个 app-loading.module.ts 移动到核心库中,但我无法引用 environment.ts。

标签: angularfunctionconfiguration

解决方案


推荐阅读