Today we are going to learn how to run an angular service in bootstrap process, that’s mean your angular app will not be loaded until a service in not running.

There could be many ways to do a task, but here we are going to do it by “APP_INITIALIZER” method, the reason is because it accepts Promises and wait until a promise is not resolved.

https://youtu.be/numYKpvkgc4

Creating a service

First of all we will create a service “ServerConfig” by following command

ng g s ServerConfig

As you know ‘g’ stands for Generate and ‘s’ is for Service.

Define init function

Inside the service file we have created a function init() which promise to return a Boolean, which will be returned in 5 seconds

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

@Injectable({
  providedIn: 'root'
})
export class ServerconfigService {

  constructor() { }

  init() : Promise<Boolean>
  {
    return new Promise<Boolean>((resolve)=>{
      setTimeout(() => {
        console.log("Service is running");
        resolve(true);
      }, 5000);
    });    
  }
}

And here a console log will be shown after 5 seconds

Modify app.module

Inside providers section of app.module.ts we are going to do following tasks.

  • Inject APP_INITIALIZER token

It will tell that there is a function which is to be executed when app initialize.

  • Adding a ‘useFactory’ function

It will point to that function which will be executed while initializing. In our case we have named it as ‘initFunction’

  • Add Dependencies

As we are going to call the function of ServerConfigService.ts thats why it have Deps on ServerConfigService. If you are making any HTTP call then you would have to provide HttpClient in Deps array.

  • Setting Multi : True

When multi is true then we can have multiple APP_INITIALIZERS, and if it is set to false then new APP_INITIALIZER will override the previous one.

  • Define ‘initFunction

lastly inside the initFunction we are just calling the init() function of service

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ServerconfigService } from './serverconfig.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [ServerconfigService, {provide : APP_INITIALIZER, useFactory : initFunction, deps: [ServerconfigService] , multi : true}],
  bootstrap: [AppComponent]
})

export class AppModule {}

export function initFunction(config : ServerconfigService)
{
  return ()=> config.init();
}

You will notice during the initialization app will wait for 5 seconds and when promise is resolved then it will go further from bootstrap process.

It is useful when you have to get the information of user from server before the view is displayed.


5 Comments

AffiliateLabz · February 15, 2020 at 9:21 pm

Great content! Super high-quality! Keep it up! 🙂

    Muhammad Waleed Arshad · March 30, 2020 at 7:20 am

    Thank you so much.

cbd oil · May 6, 2020 at 9:04 am

Howdy would you mind sharing which blog platform you’re using?
I’m planning to start my own blog soon but I’m having a difficult
time choosing between BlogEngine/Wordpress/B2evolution and Drupal.

The reason I ask is because your design and style seems different then most blogs and I’m looking for something completely unique.
P.S My apologies for getting off-topic but I had to ask!

    Muhammad Waleed Arshad · May 16, 2020 at 4:35 pm

    Hi there, I used WordPress and the only reason is , its highly customizable. There’s allot of free themes and plugins are available which will add new look to your blog.

Skincell Pro Mole And Skin Tag Remover · June 30, 2020 at 7:11 am

Nice post. I used to be checking continuously this blog and I’m inspired!
Extremely useful information specifically the remaining section 🙂 I take care of such information a lot.
I used to be seeking this particular information for
a very long time. Thanks and good luck.

Leave a Reply