How to define optional InjectionToken in Angular? (No provider for InjectionToken)

I have an InjectionToken in a monorepo which some apps can provide data. The problem is that I get an error for apps that haven’t provided this token:

No provider for InjectionToken MY_TOKEN!

export const MY_TOKEN = new InjectionToken<string[]>('MY_TOKEN');

@Injectable({ providedIn: 'root' })
export class DemoService {
  constructor(
    @Inject(MY_TOKEN) public myTokenData: string[],
  ) {}
}

It only works if the app provides it:

@NgModule({
  // ...
  providers: [
    { provide: MY_TOKEN, useValue: ['Here it is!'] },
  ],
})
export class AppModule {}

The question is: How to make an optional injection token?

We can create the token like this. If it is provided in the root, it is not required in a module. Otherwise a shared module could provide it. The factory is used for the default values when no one provides their own data. In this case of a string array, I return an empty array. But it depends on the type you have. With this solution, you don’t need to provide this token in every app with dummy data. With provided in root, there is no need to provide in any module.

export const MY_TOKEN = new InjectionToken<string[]>('MY_TOKEN', {
  providedIn: 'root',
  factory: () => [],
});

I provide this Q&A because I didn’t find a suitable solution on the web. But feel free to post other solutions and hints.

Leave a Comment