APP_INITIALIZER: How, When & Where?
What’s Angular’s APP_INITILIZER ?
Purely technically, it is an instance of InjectionToken. It is a built in Injection token provided by Angular.
Not very helpful, isn’t it?
Now, let’s go check Angular docs, this is what they say about it:
A DI token that you can use to provide one or more initialization functions.
The provided functions are injected at application startup and executed during app initialization. If any of these functions returns a Promise, initialization does not complete until the Promise is resolved.
1- So in what use can is this be beneficial?
Let’s assume you have some configuration information you want to fetch from an API before the app initialization or before any pages rendering.
In other words, fetching this data in ngOnInit won’t be the solution.
As an example: loading language files, environment info or in my very specific case, fetching an object that determines which module to load.
Thank you Angular docs for the half page description you provided, but we still don’t know HOW & WHERE to use it.
2- Implementing APP_INITIALIZER in your Angular Project
IT’S A SIMPLE TWO STEP PROCESS
a- Creating the function
In my case, I chose to implement a service.
b- Importing it in app.module.ts
AND BOOM, the work is done. Now, this is one of many different ways to implementing this.
I really hope it could help somebody out there.