What is an injection token in Angular, and when would you need one instead of just injecting a class?
Short answer
An injection token is used when you want to inject something that is not a class, such as a plain configuration object or a primitive value, since Angular's dependency injection normally relies on class types as unique identifiers.
Advertisement
AModel answer
An injection token is used when you want to inject something that is not a class, such as a plain configuration object or a primitive value, since Angular's dependency injection normally relies on class types as unique identifiers. You create a token using InjectionToken and provide a matching value for it.
import { InjectionToken } from '@angular/core';
export const API_URL = new InjectionToken<string>('API_URL');
// Providing a value for the token
providers: [{ provide: API_URL, useValue: 'https://api.example.com' }]
// Injecting it elsewhere
constructor(@Inject(API_URL) private apiUrl: string) {}Real-world example
A service needs to know the correct API address to use, and instead of hardcoding it, the app provides that value through an injection token, letting different environments easily supply a different address.
Likely follow-ups
- Why can't you simply inject a plain string type the way you inject a class?
- How would you provide a different value for the same injection token in a test environment?
Related topics