W3cubDocs

/Angular 12

APP_INITIALIZER

const

A DI token that you can use to provide one or more initialization functions.

See more...

const APP_INITIALIZER: InjectionToken<ReadonlyArray<() => void | Observable<unknown> | Promise<unknown>>>;

See also

Description

The provided functions are injected at application startup and executed during app initialization. If any of these functions returns a Promise or an Observable, initialization does not complete until the Promise is resolved or the Observable is completed.

You can, for example, create a factory function that loads language data or an external configuration, and provide that function to the APP_INITIALIZER token. The function is executed during the application bootstrap process, and the needed data is available on startup.

Further information is available in the Usage Notes...

Usage notes

The following example illustrates how to configure a multi-provider using APP_INITIALIZER token and a function returning a promise.

function initializeApp(): Promise<any> {
   return new Promise((resolve, reject) => {
     // Do some asynchronous stuff
     resolve();
   });
 }

 @NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [{
    provide: APP_INITIALIZER,
    useFactory: () => initializeApp,
    multi: true
   }]
  })
 export class AppModule {}

It's also possible to configure a multi-provider using APP_INITIALIZER token and a function returning an observable, see an example below. Note: the HttpClient in this example is used for demo purposes to illustrate how the factory function can work with other providers available through DI.

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 {}

© 2010–2021 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v12.angular.io/api/core/APP_INITIALIZER