angulartypescriptdependency-injectionfactoryapp-initializer

Using the Angular inject function with a APP_INITIALIZER


With Ivy, Angular introduced the nice inject function. According to the documentation the function can be used "from a provider's factory" accompanied with the following example:

providers: [
  {
    provide: Car,
    useFactory: () => {
      // OK: a class factory
      const engine = inject(Engine);
      return new Car(engine);
    }
  }
]

This makes me believe that I can now convert my old APP_INITIALIZERs:

providers: [
  {
    provide: APP_INITIALIZER,
    useFactory: (engine: Engine) => () => engine.start(),
    deps: [Engine],
    multi: true
  }
]

using the inject function to something simpler like this:

providers: [
  {
    provide: APP_INITIALIZER,
    useFactory: () => () => inject(Engine).start(),
    multi: true
  }
]

This fails, however, giving me the following error message:

Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with EnvironmentInjector#runInContext.

Is it no longer a factory context, when using APP_INITIALIZER? Or what is the problem here?


Solution

  • Looks like a missing feature, context exists only in the top level function.

    This is working example:

    providers: [
      {
        provide: APP_INITIALIZER,
        useFactory: () => {
          const engine = inject(Engine);
          return () => engine.start();
        },
        multi: true
      }
    ]
    

    Or

    providers: [
      {
        provide: APP_INITIALIZER,
        useFactory: () => {
          inject(Engine).start();
          return () => {};
        },
        multi: true
      }
    ]