DEV Community

Harshal Limaye
Harshal Limaye

Posted on

How to use APP_INITIALIZER token in Angular

APP_INITIALIZER is a powerful feature in Angular that allows developers to perform tasks before the application starts. It is essentially a way to run code during the bootstrapping process of an Angular app. One common use case for APP_INITIALIZER is to load configuration data from a server or a local file. This data is often required for the application to function properly, and it is important to have it available as soon as possible.

To use APP_INITIALIZER, you need to import the APP_INITIALIZER token from the @angular/core module and use it to provide a factory function. This factory function should return a Promise that resolves when the initialization is complete.

Let's understand this in detail using an example:

import { APP_INITIALIZER, NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

export function loadConfig(http: HttpClient) {
  return () => http.get('/config').toPromise();
}

@NgModule({
  imports: [HttpClientModule],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: loadConfig,
      deps: [HttpClient],
      multi: true
    }
  ]
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

In this example, the loadConfig function uses the HttpClient to make a request to a server to retrieve the configuration data. The function returns a Promise that resolves when the data has been retrieved.

It is important to note that the APP_INITIALIZER factory function should be marked as multi: true, as this allows multiple initializers to be run. If you do not mark the factory function as multi: true, only the last initializer registered will be run.

And that's it! I hope you found this post useful. Incase you have any questions or queries, feel free to drop a comment.

Top comments (0)