How to use APP_INITIALIZER in Angular

APP_INITIALIZER is 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 or an Observable, initialization does not complete until the Promise is resolved or the Observable is completed.

This is typically used to loads language data or an external configuration.

Setup

Install the Angular CLI using the npm package manager.

To create, build, and serve a new, basic Angular project on a development server, go to the parent directory of your new workspace use the following commands:

In your browser, open http://localhost:4200 to see the new application run.

Use Cases

Next, Let’s look at different examples where APP_INITIALIZER can be used.

Delay

Let’s take a hypothetical case where we want the application to load with a delay of 3 seconds. Here is how the app.module.ts needs to be updated to achieve this.

Now, when you run the application, there is a delay of 3 seconds before the application renders.

If you want to load static data to your application before it initialises, use the above approach.

API

Next, Let’s take the case where we want to load some configurations from a remote API.

Add the following code to your app.module.ts.

Now, when you run the application, it renders only after the request is complete. Examine the Network tab in Developer Tools, you can see that the API call is the first thing that happens.

What if the request fails?

If the request fails, the application will not render. You can try this by providing some invalid url instead of https://api.github.com/.

To ensure the application renders even when the request fails, we can do the following and have a fallback mechanism.

How to persist response?

To persist the response, you can use a service and assign the value to a property. For example, create a service app-load.service.ts as below.

Next, update the app.module.ts as below.

Now, you can use the getConfigurations() in app-load.service.ts to access the configurations across the application.

Conclusion

The working project can be found here on Github.

Leave a Reply

Your email address will not be published. Required fields are marked *