Search code examples
angulartypescriptangular-dependency-injection

Angular optional multi interceptors - why is it injected as null?


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
}


Solution

  • 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>>