0

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?

Mikkel R. Lund
  • 2,336
  • 1
  • 31
  • 44
  • Is Engine a service or what? inject() looks through Environment Injection Hierarchy for the dependencies. Are you sure Engine is provided at this level? – mhld Jun 26 '23 at 13:09
  • Like in the documentation example, `Engine` is something that can be injected. Exactly what isn't important, but yes, it could be a service. The important thing is that it can be injected, but trying to do it with `inject` fails when using `APP_INITIALIZER`. I've changed the example slightly. – Mikkel R. Lund Jun 26 '23 at 19:02

1 Answers1

1

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
  }
]
kemsky
  • 14,727
  • 3
  • 32
  • 51