DEV Community

loading...
Cover image for Using Observable in APP_INITIALIZER
This is Angular

Using Observable in APP_INITIALIZER

dzhavat profile image Dzhavat Ushev Originally published at dzhavat.github.io ใƒป2 min read

An exciting new feature is coming to Angular v12 - support for Observables in APP_INITIALIZER ๐ŸŽ‰

Note: This feature was added in v12.0.0-next.2.

Up until now, if you wanted to execute something asynchronous as part of APP_INITIALIZER, say an HTTP request to get some configuration, your only option was to convert it to a Promise. Often times using toPromise() (which, btw, is deprecated in the upcoming RxJS v7).

This is no more! In v12 you will be able to directly return an Observable. Letโ€™s see how:

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

An important thing to note is that the Observable must complete, otherwise the bootstrap process will not continue.

Now, place the loadConfigProvider variable in the providers array of a Module and everything should be working fine. Check out this Stackblitz to see it in action.

Oh, and donโ€™t forget to add error handling to that request. ๐Ÿ˜Ž

Thanks to Yadong Xie for this wonderful contribution.


Photo by Katerina Pavlyuchkova on Unsplash

Discussion (0)

pic
Editor guide