Jeroen
Jeroen

Reputation: 63830

InjectionToken in Angular APP_INITIALIZER factory

I'm trying to create an APP_INITIALIZER in my Angular 10 application, where the factory has multiple dependencies. One dependency is an InjectionToken<string>, but I cannot inject it the way I do with constructors. I get:

Error in ...
Decorators are not valid here.

Here's how to reproduce this behavior (see also this StackBlitz example):

export const FOOBAR = new InjectionToken<string>('FOOBAR');

@Injectable({providedIn: 'root'})
export class FooService { dummy = 'value'; }

function initializerFactory(
  fooService: FooService,
  @Inject(FOOBAR) fooBar: string,
) {
  return () => {
    fooService.dummy = `Changed ${fooService.dummy}, added ${fooBar}`;
  }
}

And then this in the app.module:

providers: [
  { provide: FOOBAR, useValue: 'token value' },
  { provide: APP_INITIALIZER, useFactory: initializerFactory, multi: true, deps: [FooService, FOOBAR] },
],

How can I Inject a token into a factory method with Angular?

Upvotes: 3

Views: 2652

Answers (1)

Jeroen
Jeroen

Reputation: 63830

Just remove the @Inject(...). The deps are injected "magically" in the exact order you list them, as arguments to the function.

So this:

 {
      provide: APP_INITIALIZER,
      useFactory: initializerFactory,
      multi: true,
      deps: [FooService, FOOBAR]
 },

will inject FooService as a first argument, and FOOBAR as the second argument, into your factory.

Upvotes: 5

Related Questions