Search code examples
angulartypescriptangular11initializer

Angular - app initializer not being called


I made several changes to an Angular 11 app and now there are a few things broken that I need to fix. What I don't understand is why the app initializer that I defined is not being called at all. The changes that I made shouldn't have impacted this, so I'd be grateful for some suggestions. I did it exactly as written in the official documentation:

function initApp(http: HttpBackend, settings: AppSettings): () => Observable<any> {
  console.log("INITIALIZING APP");
  var appInfoCall = () => new HttpClient(http).get<IApplicationInfo>(settings.appInfoApi).pipe(
  tap(data => {    
    console.log("APP INITIALIZATION COMPLETE");
    settings.appInfo = data;
  }));
  return appInfoCall; 
}

and the provider array in my app.module.ts:

...,
{
  provide: APP_INITIALIZER,
  useFactory: initApp,
  deps: [HttpBackend, HttpClient, AppSettings],
  multi: true
}
],
bootstrap: [AppComponent]

From the console output I can see that the initApp function isn't called at all. Any ideas why this is the case?


Solution

  • Since initApp is expected to be injected with two providers:

    function initApp(http: HttpBackend, settings: AppSettings): () => {
      ...
    }
    

    Modify the APP_INITIALIZER provider (dep) as:

    {
        provide: APP_INITIALIZER,
        useFactory: initApp,
        deps: [HttpBackend, AppSettings],
        multi: true,
    }
    

    Sample Demo on StackBlitz


    Reference

    APP_INITIALIZER (Usage note)