How To Use APP_INITIALIZER

Da Feng
4 min readApr 21, 2022

To add some custom logic before application starts

Photo by Jukan Tateisi on Unsplash

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.

What is APP_INITIALIZER

--

--

Da Feng

I am a software developer, write blogs about Typescript, Angular, React, vue, Front-end technologies, also share some of my life stories and good memories here.