Ling Vu
Ling Vu

Reputation: 5181

Set service variables before App is rendered

I want to provide a service that sets all variables that are necessary for the all following requests. That service should make an initial request to get all information.

{
 "apiHost":
 "apiPrefix":
 "externalApiHost":
 "externalApiPrefix":
 "defaultLanguage":
}

I don't want to put anything into the ngOnInit method app.component.ts

Upvotes: 1

Views: 33

Answers (1)

sonaliii
sonaliii

Reputation: 56

imports: [
  BrowserModule,
  HttpClientModule
],
providers: [{
  provide: APP_INTIALIZER,
  useFactory: initApp,
  multi: true,
  deps: [HttpClient]
}]

and the in the init-app.ts file write the following code

export function initApp(http: HttpClient) {
  return () => {
    return http.get('https://xxxxx-xxxx')
      .toPromise()
      .then((resp) => {
        console.log(`initialize your app`);
      });
  };
}

Upvotes: 2

Related Questions