-1

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;
  }
}
user1005310
  • 737
  • 2
  • 12
  • 40
  • yes, thank you, this is how my function looks now loadConfig(){ return this.http.get("/assets/data/appConfig.json").pipe(tap(value => this.config = value)); } – user1005310 Jan 16 '22 at 01:28

1 Answers1

3

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 {}
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90
  • this worked, thanks for direction loadConfig(){ return this.http.get("/assets/data/appConfig.json").pipe(tap(value => this.config = value)); } – user1005310 Jan 16 '22 at 01:28
  • OMG thanks for a simple and straight forward solution that works! Easily understandable too. – Arizon Sep 01 '23 at 18:25