APP INITIALIZER in Angular5

Posted By : Himanshu Khurana | 30-Apr-2019

Angular will allow the function to finish running before rendering anything. It can even be improved, and if an error is found, the entire application will not load. This ensures that your remote load configuration is available from the start. You can use it to load whatever you want during the initialization phase, so it will be available immediately after the application is launched.

 

APP_INITIALIZER: This function is called when the angular application is initialized. To do this, we need to import from the core in the Application module.

 

Inject APP_INITIALIZER when you need to initialize our application from the server call. Angular will perform the functions provided when the application is initialized. If the function returns a promise until the promise is resolved, Angular will wait for initialization.

 

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

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppService } from './app.service';

export function init_app(appService: AppService ) {
    return () => appService.initializeApp();
}
@NgModule({

 providers: [
    appService,
    { provide: APP_INITIALIZER, useFactory: init_app, deps: [appService], multi: true }
  ]

})
        

 

In the above code, we must first import APP_INITIALIZER from '@angular/core'. Now we export the factory "init_app". We have added the custom service dependency "AppService" and the last parameter for a multi-token for a true and single token for false.

 

Our app service code.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AppService{
  constructor(private httpClient: HttpClient) { }
  initializeApp(): Promise {
    return new Promise((resolve, reject) => {
          console.log('initialize App');
	    // here you can get the data from server
            resolve();
        });
  }
}
    

 

In the above code, we can easily create a personalized service and create a function with a promise, so it will execute first and then our application will start. You can compile the code and verify the results of the logged in code in the console.

 

If you want to get data from the server, you need to generate the following code.

const responseData = this.httpClient.get('enter the url')
      .toPromise()
      .then(res => {
        console.log('response');
        return res;
      });

    return responseData;


  

 

Thanks

 

About Author

Author Image
Himanshu Khurana

Himanshu is an experienced Frontend developer with experience and capabilities to build compelling UI's for Web and Mobile Applications. Himanshu likes playing cricket and listening music.

Request for Proposal

Name is required

Comment is required

Sending message..