在APP_INITIALIZER上的应用程序初始化后加载appsettings.json文件

我一直试图在DevOps上部署Angular 8应用程序,并在.json文件中使用配置,以便不针对不同的环境重新构建整个应用程序。

我使用以下2个帖子来创建所有配置:

Continuously Deploying Angular to Azure App Service with Azure DevOps

和堆栈溢出答案:

App.settings - the Angular way?

Note that I'm not interested on using the environment.ts way, as this way will require me to re-build the solution for each environment.

因此,我准备了所有这样的代码:

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule
    ],
    providers: [
        {
             provide: APP_INITIALIZER,
             useFactory: (appConfigService: ConfigService) => {
             return () => {
                //Make sure to return a promise!
                return appConfigService.loadAppConfig();
             };
          },
          deps: [ConfigService],
          multi: true
       }
    ],
    bootstrap: [AppComponent]
 })
 export class AppModule {}

My ConfigService.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ConfigService {
private appConfig: any;

constructor(private http: HttpClient) {}

loadAppConfig() {
  return this.http.get('./assets/appconfig.json')
    .toPromise()
    .then(config => {
      this.appConfig = config;
    });
}

get apiBaseUrl() {
    if (!this.appConfig) {
      throw Error('Config file not loaded!');
    }

    return this.appConfig.apiUrl;
  }
}

然后,需要加载appconfig.json信息的主要对象:

  export class ApiService {
  apiUrl: string;

     constructor(private readonly httpClient: HttpClient,
          private configService: ConfigService) { 
            this.apiUrl = this.configService.apiBaseUrl;
     }

     ngOnInit() {
       this.apiUrl = this.configService.apiBaseUrl;
     }    
  }

但是随后,在加载应用程序时,会出现以下消息:

enter image description here

If I debug the app, the appsettings.json file is loading info, but then it looks like the angular init is happening before loading the appsettings.

我做错了什么?

评论
  • 俄对花儿笑
    俄对花儿笑 回复

    You can return a Promise and resolve it inside the subscribe callback of HTTP request as followings:

    loadAppConfig() {
      return new Promise((resolve) => {
         this.http.get('./assets/appconfig.json').subscribe(config => {
            this.appConfig = config;
            resolve();
         })
      });
    }