根据 API 输出在 Angular 6 中设置全局变量

Set Global Variables in Angular 6 as per the API output

基本上,我需要 environment.ts 文件来一次性调用外部 API,然后我想在我的 global.ts 文件中设置该变量,然后我将使用它在全球范围内的各种组件中。 通过在 environment.ts 中添加静态值,我可以在没有 API 调用的情况下实现它。我需要根据 API.

使其动态化

例如,我有 environment.ts 作为,

export const environment = {
  defaultCountry: 'US',
};

然后我在 global.ts 中使用它,

defaultCountry: environment.defaultCountry,

我想使这个 defaultCountry 动态基于 API 之类的东西,

export const environment = {
      defaultCountry: this.api.subscribe() == true? 'US': 'CA',
    };

如果这种方法不正确,请您建议我如何实现它,因为我无法从 environment.ts 文件中调用 API。 在此先感谢您。

编辑:此外,这应该在应用程序启动时设置,如果 API 失败,它不应该抛出任何异步错误。

通过使用 APP_INITIALIZER ,我能够解决我的问题...

1.Added app.module.ts 中的以下代码:

{
      provide: APP_INITIALIZER,
      useFactory: (configService: ConfiguartionService) =>
        () => configService.loadConfigurationData(),
      deps: [ConfiguartionService],
      multi: true
    }

2.Created ConfigurationService,它将调用 API 并获取数据,

loadConfigurationData(): Promise<any> {
    return this.http.get<any>("your api").toPromise().then((result) => {
      this.configData = result.data;
    })
  }

3.Fetched 任何组件中的配置数据变量,

this.config = this.configService.config;

参考: hackernoon