1

Basically, I need environment.ts file to make an one time call to external API and then I want to set that variable in my global.ts file, which then I will use in various components globally. I can achieve it without API call by adding static values in environment.ts. I need to make it dynamic based on API.

For Example, I have environment.ts as,

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

Then I am using this in global.ts as,

defaultCountry: environment.defaultCountry,

I want to make this defaultCountry dynamic based on API something like,

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

If this approach is not correct, can you please suggest me how can I achieve it as I can't call API from environment.ts file. Thank you in Advance.

Edit: Also, this should be set on application start, and it should not throw any async error if API fails.

elpidaguy
  • 624
  • 1
  • 11
  • 25

1 Answers1

3

By Using APP_INITIALIZER , I was able to solve my problem...

1.Added following code in app.module.ts:

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

2.Created ConfigurationService, which will call API and fetch data as,

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

3.Fetched configdata varible in any component as,

this.config = this.configService.config;

Reference: stackoverflow hackernoon

elpidaguy
  • 624
  • 1
  • 11
  • 25