Observables Now Work in APP_INITIALIZER

A highly anticipated capability is arriving in Angular v12 β€” support for Observables within APP_INITIALIZER πŸŽ‰

Note: This functionality first appeared in v12.0.0-next.2.

Previously, performing any asynchronous operation inside APP_INITIALIZER β€” for example, fetching configuration data via an HTTP call β€” meant you had to wrap it in a Promise. A common workaround was toPromise(), which, incidentally, is marked as deprecated in the upcoming RxJS v7.

That limitation is now gone. Starting with v12, you can return an Observable straight from APP_INITIALIZER. Here's how it looks:

import { APP_INITIALIZER, FactoryProvider } from '@angular/core';
import { ConfigService } from "./config.service";

function loadConfigFactory(configService: ConfigService) {
  // Easy as pie πŸ₯§
  return () => configService.getConfig(); // πŸ‘ˆ

  // How you might've done it β€œbefore”
  // return () => configService.getConfig().toPromise();
}

export const loadConfigProvider: FactoryProvider = {
  provide: APP_INITIALIZER,
  useFactory: loadConfigFactory,
  deps: [ConfigService],
  multi: true
};
Enter fullscreen mode Exit fullscreen mode

One critical detail: the Observable has to complete. If it doesn't, the bootstrap process will stall indefinitely.

To activate it, just add the loadConfigProvider variable to the providers array in your module, and everything works as expected. You can see a live demo on Stackblitz.

One more thing β€” make sure you include proper error handling for that HTTP request. 😎

Credit goes to Yadong Xie for this excellent contribution.


Photo by Katerina Pavlyuchkova on Unsplash