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. As long as 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 uses this mecanism :