How to call an asynchronous service before bootstrap ?

Sometimes, we have to fetch datas before our application boostrap is started. It happens when we have to fetch a server configuration before calling an API. Angular offers a poorly documented system : the APP_INITIALIZER provider.

APP_INITIALIZER is a multi provider, that is, a provider that accepts several values. But this provider is special because it accepts promises. While all promises aren’t resolved, your application will wait. It’s a good place for fetching a configuration !

Suppose we have a service that would search for a configuration on a remote server. To simulate the http request, we will use the asynchronous method setTimeOut. Here is our service :

Now, we would like to call the load method before the application bootstrap. Thus, a component can use this service during the bootstrap ! APP_INITIALIZER will play this role. But, how to configure this provider ? This is not trivial, so here is the configuration :

Then, during the initialization stage, Angular will execute the load function. Here is the Angular code that wait to resolve promises :

This is a plunker that use this mecanism :

Like what you read? Give a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.