To add some custom logic before application starts
Why we need it
It’s common that before an application starts, it needs to know in advance quite a few configurations, such as what’s the baseURL
of http call, what's the port number
etc. These configurations can also differ between defferent environtments (dev or prod). In angular we do this by putting these configuration constants into a environment ts file, and differenciate them into environment.dev.ts
and environment.prod.ts
. So when we build the appliaction with ng build -configuration <production or development>
, the according environment file will be replaced and used, and when the app starts up, it knows the right constants to use.
But this won’t always satisify our requirements in real life. Imagine this interesting and fair use case: In some complicated apps sometimes frontend routers need to be dynamically configurable according to a backend http call. Or simply we might need to make one of the constants that we put in environment file to be dynamically configurable through a http call.
That’s why in this case we need APP_INITIALIZER
, it makes sure that we can apply some logic and get that result back before app starts, otherwise the app will keep loading.