APP_INITIALIZER usage in Angular

APP_INITIALIZER usage in Angular

APP_INITIALIZER is run when the application starts to initialized. Angular suspend the app initialization until all the funciton provided by the APP_INITALIZER are run. if any of the initializers returns a promise then the angular waits for it to resolve, before continuing with the app initialization.


import { Injectable }  from  @angular/core ;

  providedIn:  root 
export class AppInitService { 
    constructor() {
    Init() {
        return new Promise((resolve, reject) => {
            console.log("AppInitService.init() called"); 
            setTimeout(() => {
                console.log( AppInitService Finished );
            }, 6000);


import { BrowserModule } from  @angular/platform-browser ;
import { NgModule, APP_INITIALIZER } from  @angular/core ;
import { HttpClientModule } from  @angular/common/http ;

import { AppRoutingModule } from  ./app-routing.module ;

import { AppComponent } from  ./app.component ;
import { AppInitService } from  ./app-init.service ;

export function initializeApp1(appInitService: AppInitService) {
  return (): Promise => { 
    return appInitService.Init();

  declarations: [
  imports: [
  providers: [ 
    { provide: APP_INITIALIZER,useFactory: initializeApp1, deps: [AppInitService], multi: true}
  bootstrap: [AppComponent]
export class AppModule { }

we need to execute the appInitService.Init(). we cann't do it directly from the provider. need to create separate function which invoke the appInitService.Init() are returns a Promise.

Register the dependency in the provider using token, the token eithe type, a string or a instace of InjectionToken

Type token

providers :[{ provide: productService, useClass: productService}]

string token

providers :[ {provide:'MESSAGE', useValue: 'Hello Message'}]

Angular Dependency injection injects to dependencies to classes & components, not a function. The useFactory is used because initializeApp1 is a function AppInitService to be injected as the argument. We do that by using the deps: flag and let angular know that it needs to create a instance of AppInitService and inject it to the initializeApp1 function. The multi : true create the multi provider


Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed