0

Given a multi injectable defined like below, without any providers, I would expect the injected list to be empty, but in reality it is null.

Is there a way to inject the value as [] instead of null if there are no providers for this injectable? I can't override the value in the constructor, because the code in the constructor runs AFTER the field initializers, so the error happens before I can correct the value.


const MY_INTERCEPTORS: InjectionToken<MyInterceptor> = new InjectionToken('MyInterceptors');


@Injectable()
export class MyService {
  constructor(
    @Optional() @Inject(MY_INTERCEPTORS) private readonly interceptors: MyInterceptor[]
  ) {
    super();
  }

  public myField$(input: Foo) = this.interceptors.reduce((agg, e) => e.intercept(agg), input);  // Expect this.interceptors to be [], but is null
}

Ákos Vandra-Meyer
  • 1,890
  • 1
  • 23
  • 40
  • 1
    Angular doesn't support default values with @Optional decorator. Proposal is here https://github.com/angular/angular/issues/25395 – leonmain Apr 07 '23 at 07:40

1 Answers1

1

You can provide a factory to your InjectionToken. It will be used as default value

const MY_INTERCEPTORS: InjectionToken<Array<MyInterceptor>> = new InjectionToken('MyInterceptors', {
    factory: () => [],
});

And by the way, the type of InjectionToken should be array

const MY_INTERCEPTORS: InjectionToken<Array<MyInterceptor>>
leonmain
  • 336
  • 1
  • 3