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:
Then, when I used @NgModule() to set up my module, I specify a provider for APP_INITIALIZER which uses this function to be called:
And that's all there is to it. :)
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
Post a Comment