1

I want to load the firebaseConfig asynchronously because I want to seperate config from artifact, to be able to have a clean CI/CD pipeline (build once, run on any environment, get config from server).

But to use firebase I need to call provideFirebaseApp(() => initializeApp(firebaseConfig)) inside of the imports of my AppModule. How can I do this if firebaseConfig must be loaded asynchronously?

What I would like to do:

let config: { firebase: any };

function initializeAppFactory(httpClient: HttpClient): () => Observable<any> {
  return () => httpClient.get('https://myserver.com/api/config').pipe(c => config = c)
}

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    provideFirebaseApp(() => {
      return initializeApp(config.firebase); 
      // THIS DOES NOT WORK, because the APP_INITIALIZER is async! How can we also make this import async?!?
    })],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [{
    provide: APP_INITIALIZER,
    useFactory: initializeAppFactory,
    deps: [HttpClient],
    multi: true,
  }],
})

Patric
  • 1,489
  • 13
  • 28
  • 1
    Hi, tried to find any docs or information about your issue. Honestly looks like there is no clean way to do this but there is a similar question: https://stackoverflow.com/questions/54469571/angular-load-external-configuration-before-appmodule-loads Take a look at all the answers, accepted one has some issues as they tell. – Sergey Sosunov Jul 10 '22 at 22:47
  • 1
    https://stackoverflow.com/a/69614605/17427052 what about this? – GRD Jul 11 '22 at 06:57

1 Answers1

0

Found a satisfying solution :D

In main.ts, I can load the config from the server and write it to e.g. my environment file:

(async () => {
  environment.appConfig = await fetch(environment.apiUrl + 'environment/frontend-config/myApp').then((res) => res.json());
  platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .catch((err) => console.error(err));
})();

And then I dont even need an app initializer, I can just use the environment file as I usually would:

provideFirebaseApp(() => {
  return initializeApp(environment.appConfig.firebase); 
})],

To make it even nicer I wrapped it all in a configService that is available in all my apps.

Patric
  • 1,489
  • 13
  • 28