首页 > 解决方案 > APP_INITIALIZE 后初始化模块

问题描述

在我的 Angular 6 应用程序中,我正在通过这样的 Http 服务加载我的外部化配置:

export function getSettings(appLoadService: ConfigLoadService) {
  return () => appLoadService.getSettings();
}

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  providers: [
    ConfigLoadService,
    {provide: APP_INITIALIZER, useFactory: getSettings, deps: [ConfigLoadService], multi: true}]
})
export class AppLoadModule {
}

服务:

@Injectable()
export class ConfigLoadService {

  constructor(private http: HttpClient) {
  }

  getSettings(): Subscription {
    console.log("Loading config from server...");
    return this.http
      .get("/config.json")
      .subscribe((config: any) => {

        AppSettings.API_BASE_URL = config.API_BASE_URL;

        console.log("API_BASE_URL: " + AppSettings.API_BASE_URL);
      });
  }
}

现在我想添加一个外部依赖项,该依赖项需要使用现有配置进行初始化:

@NgModule({
  imports:
    DepModule.forRoot({
      apiBaseUrl: AppSettings.API_BASE_URL
    }),
  ],[...]

这里的问题是依赖项是在 之前导入和初始化的APP_INITIALIZER,因此没有正确配置。我在这里想念什么?

标签: angular

解决方案


提供APP_INITIALIZER者工厂方法必须返回一个承诺

所以你会做这样的事情:

@Injectable()
export class ConfigLoadService {

  private myConfig;
  constructor(private http: HttpClient) {
  }
  getSettings() {
    return this.http.get('/config.json')
      .toPromise()
      .then(data => {
        this.myConfig = data;
      });
  }

  getConfig() {
    return this.myConfig;
  }
}

Juri 写了一篇关于它的博客,您可以阅读更多App Runtime Config


推荐阅读