Angular · Middle · Question 23 of 75
Why use an InjectionToken?
export const API_URL = new InjectionToken<string>("API_URL");
// providers: [{ provide: API_URL, useValue: "https://api.example.com" }]
// usage: private apiUrl = inject(API_URL);- ✓Correct answer: To inject values that have no class to use as a token: strings, config objects, functions
- 2To encrypt values stored in services
- 3To make a service available only in tests
Explanation
Interfaces disappear at runtime, so they can't be DI tokens. An InjectionToken is a unique runtime key that also carries the TypeScript type.