How to use APP_INITIALIZER in Angular?

APP_INITIALIZER : this function is called when angular app is initialized. For that we need to import from the core in our Application module.

APP_INITIALIZER injection is used for when ever you need to call from server initialized our applocation. Angular will execute provided function when the app is initialized. Angular will wait for the initialization if the function returns a promise until the promise resolved.


First we need to add in our app.module.ts file.


..........
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { MyAppLoadService } from './myapp-load.service';
.........
export function init_app(firstLoadService: MyAppLoadService ) {
    return () => firstLoadService.initializeMyApp();
}
@NgModule({
.........
 providers: [
    MyAppLoadService,
    { provide: APP_INITIALIZER, useFactory: init_app, deps: [MyAppLoadService], multi: true }
  ]
....
})

In above code we need to first import the APP_INITIALIZER from ‘@angular/core’. We now export Factory “init_app”. We have added dependency of “MyAppLoadService” custom service and last parameter for multi token for true and single token for false.


Creating Our MyAppLoadService code.


//import injectable from core.
import { Injectable } from '@angular/core';

// below v4 we need to import 
//import { Http, Response, Headers, RequestOptions } from '@angular/http';
//Angular 4+ we need to import from common.
import { HttpClient } from '@angular/common/http';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class MyAppLoadService{

  constructor(private httpClient: HttpClient) { }

  initializeMyApp(): Promise {
    return new Promise((resolve, reject) => {
          console.log('initialize MyApp');

          setTimeout(() => {
            //code here from call from server data

            resolve();
          }, 3000);
        });
  }

  
}

In above code we can easily create custom service and creating function with promise so it will first execute then our app will initialize. You can compile code then check in the console for output that we have log in the code.
If you want to get from server data the you need to do code like below.


 const response = this.httpClient.get('URL from where you want to get data')
      .toPromise()
      .then(res => {
        console.log('Response from server API: ', res );
        return res;
      });

    return response;

Above code you can easily get data from server.

Spread the love
  • 18
  •  
  •  
  •  
  •  
  •  
  •  
  •