How To Set Up Extra Application Initialization in an Angular App

Angular includes a constant called APP_INTIALIZER. As of the time of this writing, the Angular docs page on it looks like this:


I'm pretty sure they've updated the page since the first time I looked at it, at which point it said even less than what is shown above. And even the expanded documentation above isn't exactly clear as to how to use this. So I'll elaborate.

In your app's module file, you can declare a provider that provides APP_INITIALIZER. And you can tell it to use a certain function via the useFactory property.

For example, in my app.module.ts, I import my environment constant which contains environment-specifc config settings, and I've declared a function called initializeApp() which initializes my AppConfigService with envrionment:

import { environment } from '../environments/environment';

export function initializeApp(appConfigSvc: AppConfigService) {
return () => {
appConfigSvc.init(environment);
}
}

Then, when I used @NgModule() to set up my module, I specify a provider for APP_INITIALIZER which uses this function to be called:

providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
deps: [AppConfigService],
multi: true
}
]

And that's all there is to it. :)

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

Silent Renew and the "login_required" Error When Using oidc-client

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

How to Determine if a Column Exists in a DataReader