How to use APP_INITIALIZER token in Angular Application

How to use Angular APP_INITIALIZER token to execute functions during bootstrapping application

In this article, we’re going to learn how to use Angular APP_INITIALIZER injection token.

Now you might be wondering what’s APP_INITIALIZER injection token and where it is used.

What is APP_INITIALIZER injection token

APP_INITIALIZER is an injection token that allows you to provide one or more initialization functions.

These functions are injected at application startup and executed during app initialization.

If any of these functions return a Promise, initialization does not complete until the Promise is resolved.

When APP_INITIALIZER is used

When you want to load the application configuration when the application starts, you’ll need to use APP_INITIALZER.

It’ll allow you to provide a function which will be executed during the application bootstrap process.

If the function that you provided will throw an error, the application will not be loaded. This ensures that the configuration will always be read when your application is loaded.

so it useful when you want to load some data before application starts. For example, you might want some settings like apiUrl, apiKey, imageBaseUrl, languages etc.

Now we’ll see how to use APP_INITIALIZER in Angular Application

Create Angular Application

Run the following command to create a new application.(assuming you’ve already installed angular cli and if not then first install angular cli and then run the following command)

ng new angular-appinitializer-demo

Navigate to project directory

cd angular-appinitializer-demo

Now create configuration service by the following command

ng generate service configuration

We’ll use this service to fetch the configuration that we needed before application starts.

Our service will look like this

configuration.service.ts

import { Injectable, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ConfigurationService { private configSettings: any = null; constructor(private readonly httpClient: HttpClient) { } get settings() { return this.configSettings; } loadConfigurationSettings() { return new Promise((resolve, reject) => { this.httpClient .get("https://api.github.com/users/elitecorner") .subscribe((response: any) => { this.configSettings = response; console.log("Configuration Loaded", this.configSettings); resolve(true); }); }); } }

Here, we’ve created a method called loadConfigurationSettings() which will call api to get the configuration settings that we needed when the application starts. We’ll call this method from factory. But for the simplicity, we’ll call github api to get the user information here.

This service use HttpClient which will call out api endpoint and will get a settings from that api endpoint. As we are using HttpClient, we’ll need to import HttpClientModule in app.module.ts

Configuring APP_INITIALIZER

Now we’ll add APP_INITIALIZER provider in app.module.ts as following

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 { ConfigurationService } from './configuration.service'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [{ provide: APP_INITIALIZER, useFactory: configurationProviderFactory, multi: true, deps: [ConfigurationService] },], bootstrap: [AppComponent] }) export class AppModule { } export function configurationProviderFactory(configService: ConfigurationService) { return () => configService.loadConfigurationSettings(); }

As you can see in the above code, we’ve added provider in providers array.

provide: APP_INITIALIZER

It indicates that we’re providing APP_INITIALIZER.

userFactory: configurationProviderFactory.

That means we’re using factory provider. Also check we’ve created factory function.

multi: true

It means we could have multiple APP_INITIALIZER providers, not just this single provider.

deps: [ConfigurationService]

It means we’re injecting ConfigurationService as dependency.

Our app.component.ts will log App Component initialized as following:

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(){ console.log('App Component initialized') } }

That’s It, we’ve successfully implemented APP_INITIALIZER token.

Output

Now if you’ll run the application using ne serve, you can see that below output.

As you can see in the above image, It has first fetched the github user and then “App component is initialised.”

I hope you like this article

Also Read