How to run initialization tasks before loading an Angular application?

Alain Chautard
Angular Training
Published in
2 min readApr 29, 2021

--

Sometimes, we need to load some information upfront, right from the time our application starts. We want to make sure that such information is available synchronously right from the beginning and then for the application's entire life cycle.

For instance, we might need to load environment variables from a server or any external configuration data from a third-party API.

Enter the APP_INITIALIZER injection token

The APP_INITIALIZER injection token is a way to provide a factory function that performs initialization tasks.

Such tasks will run during the application bootstrap process, and the resulting data will be available on startup.

In the following example, I’m adding a provider definition to app.module.ts using the APP_INITIALIZER injection token:

{provide: APP_INITIALIZER, useFactory: loadRemoteEnv, multi: true}

In that example, loadRemoteEnv is the function that will run upon initialization.

If we need to inject dependencies to that factory function, we can use the following syntax. Here I’m injecting the HttpClient service as a dependency:

{provide: APP_INITIALIZER, useFactory: loadRemoteEnv, deps: [HttpClient], multi: true}

Those dependencies are listed in an array, which means you can add as many as you need. The factory function will be called with those dependencies passed as parameters.

In my example, the initialization function looks like this:

export function loadRemoteEnv(http: HttpClient) {
return () => {
return new Promise<Environment>((resolve) => {
console.log(`Initializing remote env variables`);
http.get('environment.json').toPromise().then(result =>
ENV_DATA = result;
resolve();
)
}
}

Note that if the task you want to perform is asynchronous, Angular will wait for that task to complete as long as your initialization function returns a promise, as illustrated in the above example.

My name is Alain Chautard. I am a Google Developer Expert in Angular, as well as consultant and trainer at Angular Training where I help web development teams learn and become comfortable with Angular.

If you enjoyed this article, please clap for it or share it. Your help is always appreciated.

--

--