How To Use APP_INITIALIZER In Angular

How To Use APP_INITIALIZER In Angular

We examine what APP INITIALIZER is in this article and how to use it in Angular applications. By building an example app, we'll demonstrate how to use it.

What is APP_INITIALIZER

An instance of InjectionToken is the APP INITIALIZER. It is an injection token that is already incorporated into Angular.

When the application loads, Angular will run the function given by this token. Angular will wait until the promise is resolved if the function returns a promise. Because of this, it will be the perfect location to implement some startup logic before the application is started.

Where to use APP_INITIALIZER

The APP INITIALIZER is launched when the application is initialized, as was already explained. Until all of the APP INITIALIZER's supplied functions are used, Angular suspends the initialization of the app. Before continuing with the initialization of the App, Angular waits for any promises returned by those initializers to resolve.

We now have the chance to run some of our application's custom logic by hooking into the initialization procedure. Runtime configuration data can be loaded. import critical information from the backend, etc.

Example

Create a new Angular Application

Create an app-init.service.ts file in the src/app folder.

import { Injectable }  from '@angular/core';
 
@Injectable()
export class AppInitService {
 
    constructor() {
    }
    
    Init() {
 
        return new Promise<void>((resolve, reject) => {
            console.log("AppInitService.init() called");
            ////do your initialisation stuff here  
            setTimeout(() => {
                console.log('AppInitService Finished');
                resolve();
            }, 6000);
 
        });
    }
}

There is only one method, Init, in this straightforward service. A Promise is returned by the method.

return new Promise<void>((resolve, reject) => {

A timer that waits 6000 milliseconds inside the procedure before calling the resolve

Open the app.module.ts

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 { AboutUsComponent } from './about-us.component';
import { HomeComponent } from './home.component';
import { ContactUsComponent } from './contact-us.component';
 
import { AppInitService } from './app-init.service';
 
export function initializeApp1(appInitService: AppInitService) {
  return (): Promise<any> => { 
    return appInitService.Init();
  }
}
 
@NgModule({
  declarations: [
    AppComponent, AboutUsComponent,HomeComponent,ContactUsComponent
  ],
  imports: [
    HttpClientModule,
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [ 
    AppInitService,
    { provide: APP_INITIALIZER,useFactory: initializeApp1, deps: [AppInitService], multi: true}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

First, import APP INITIALIZER from @angular/core.

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

We must run the appInitService.Init(). We are unable to do it straight from the provider. A function that calls appInitService.Init() and returns a Promise must be written. In the initializeApp1 method, we accomplish that.

import { AppInitService } from './app-init.service';
 
export function initializeApp1(appInitService: AppInitService) {
  return (): Promise<any> => { 
    return appInitService.Init();
  }
}

Finally,. To supply the initializeApp1 command, use the APP INITIALIZER token.

providers: [ 
  AppInitService,
  { provide: APP_INITIALIZER,useFactory: initializeApp1, deps: [AppInitService], multi: true}
],

InitializeApp1 is a function, not a class, hence the useFactory is used. This function is executed by the Angular Injector, which then calls the appInitService.init().

Dependencies are injected into classes and components but not functions using the Angular Dependency injection. However, because initializeApp1 is a function, it requires the injection of AppInitService as an argument. We accomplish this by instructing Angular to create an instance of the AppInitService and inject it into the initializeApp1 function by using the deps: flag.

The multi-provider DI token is created when multi:true is set. Consequently, you can offer a variety of providers for a DI token.

If multi:false (the default setting) is set and a token is used more than once, the most recent registration will take precedence.

The angular app won't launch if you return refuse from the service.

How To Use APP_INITIALIZER In Angular

Multi Providers in APP_INITIALIZER

To create a Multi Provider token, use the multi: true option. This implies that we can build several functions or services and call them all at once during initialization.

Make a second factory method called initializeApp2 that, after a timeout of 2000 milliseconds, simply writes to the console.

export function initializeApp2() {
  return (): Promise<any> => {
    return new Promise((resolve, reject) => {
      console.log(`initializeApp2 called`);
      setTimeout(() => {
        console.log(`initializeApp2 Finished`);
        resolve();
      }, 2000);
    });
  };
}

As seen below, register it next with the APP INITIALIZER token.

providers: [ 
  AppInitService,
  { provide: APP_INITIALIZER,useFactory: initializeApp1, deps: [AppInitService], multi: true},
  { provide: APP_INITIALIZER,useFactory: initializeApp2, multi: true}
],

Run the app. The following will be seen by you:
  1. InitializeApp1 and InitializeApp2 execute one after the other without pausing.
  2. Despite being called after initializeApp1, initializeApp2 completes execution first.
  3. In order for both functions to complete, Angular waits.

APP_INITIALIZER Example In Angular

Conclusion

An instance of InjectionToken is the APP INITIALIZER. It enables us to run custom logic, such as fetching some crucial data, by hooking into the Angular Initialization process.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post