从角度7配置中插入API_BASE_URL

时间:2019-04-01 16:51:53

标签: angular initialization config

我正在使用es6 Javascript版本和Swagger开发Angular 7应用程序。

我正在尝试将配置添加到app.module中的APP_INITIALIZER:

export class SettingsProvider {
  private config: AppConfig;
  constructor(private httpClient: HttpClient) {}

  public loadConfig(): Promise<any> {
        return this.httpClient.get(`assets/configs/config.json`).pipe(
          map(res => res as AppConfig))
          .toPromise()
          .then(settings => {
            this.config = settings;
          });
      }

   public get configuration(): AppConfig {
     return this.config;
   }
 }

在app.module中:

{ provide: APP_INITIALIZER, useFactory: init, deps: [SettingsProvider], multi: true },
{ provide: API_BASE_URL, useFactory: baseApiUrlSetting, deps: [SettingsProvider], multi: true },

export function init(settingsProvider: SettingsProvider) {
  return () => settingsProvider.loadConfig();
}

export function baseApiUrlSetting(settingsProvider: SettingsProvider) {
  return settingsProvider.configuration.baseApiUrl;
}

一切正常,直到我注入API_BASE_URL令牌。编译器可能尚未完成加载配置的工作,因此settingsProvider的值始终为null。

  

无法读取未定义的属性'baseApiUrl'

有人知道一个可能的解决方案吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,最终得到了以下解决方案:

main.ts

    AppConfigService.loadConfig().then(() => {
      return platformBrowserDynamic().bootstrapModule(AppModule);
    })

app-config-service.ts

import { Injectable } from '@angular/core';
import { AppConfig } from './app-config.models';

@Injectable({ providedIn: 'root' })
export class AppConfigService<T extends AppConfig = AppConfig> {
  static appConfig: AppConfig;

  constructor() { }

  static loadConfig(): Promise<void> {
    return new Promise((resolve, reject) => {
      const oReq = new XMLHttpRequest();
      oReq.addEventListener('load', (resp) => {
        if (oReq.status === 200) {
          try {
            AppConfigService.appConfig = JSON.parse(oReq.responseText);
          } catch (e) {
            reject(e);
          }
          resolve();
        } else {
          reject(oReq.statusText);
        }
      });
      oReq.open('GET', '/assets/configs/config.json');
      oReq.send();
    });
  }

  getConfig(): T {
    return AppConfigService.appConfig as T;
  }
}

app-config.models.ts

export interface AppConfig {
    ApiBaseUrl: string;
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { API_BASE_URL } from './nswag-client.service';
import { AppConfigService } from '../app-config-service';

export function getApiBaseUrl(): string {
  return AppConfigService.appConfig.ApiBaseUrl;
}

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    ...
  ],
  providers:
    [
      {
        provide: API_BASE_URL,
        useFactory: getApiBaseUrl
      },
      ...
    ],
  bootstrap: [AppComponent]
})
export class AppModule { }

转为michael-lang https://github.com/ngrx/platform/issues/931