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
}

1

1 Answer 1

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>>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I'll try this later today. It sounds like the correct answer, thank you
Confirmed working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.