Home > Enterprise >  APP_INITIALIZER load service call Angular 13
APP_INITIALIZER load service call Angular 13

Time:01-16

I am using Angular 13 and trying to hook into Angular’s bootstrapping phase by using the APP_INITIALIZER token.Need to create angular service that handles the fetching of our remote configuration, But the issue is topromise is no longer supported , its deprecated , how do I re write this loadAppConfig() method since APP_INITIALIZER only supports promises. Any help is highly appreciated.

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

@Injectable()
export class AppConfigService {
  private appConfig;

  constructor(private http: HttpClient) { }

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

  getConfig() {
    return this.appConfig;
  }
}

CodePudding user response:

APP_INITIALIZER handles both promises and observables, from the documentation: https://angular.io/api/core/APP_INITIALIZER

"If any of these functions returns a Promise or an Observable"

Their second example shows an observable:

function initializeAppFactory(httpClient: HttpClient): () => Observable<any> {
 return () => httpClient.get("https://someUrl.com/api/user")
   .pipe(
      tap(user => { ... })
   );
}

@NgModule({
  imports: [BrowserModule, HttpClientModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [{
    provide: APP_INITIALIZER,
    useFactory: initializeAppFactory,
    deps: [HttpClient],
    multi: true
  }]
})
export class AppModule {}
  •  Tags:  
  • Related