Angular course · Module 5: Services and DI
Injection Tokens and Advanced DI
In this lesson3
Injection Tokens
Tokens allow injecting values other than classes:
import { InjectionToken, inject } from '@angular/core';
// Token definition
export const API_URL = new InjectionToken<string>('API_URL');
export const FEATURE_FLAGS = new InjectionToken<FeatureFlags>('FEATURE_FLAGS');
// Registration in configuration
export const appConfig: ApplicationConfig = {
providers: [
{ provide: API_URL, useValue: 'https://api.dojo.com/v1' },
{
provide: FEATURE_FLAGS,
useValue: {
darkMode: true,
newDashboard: false
}
}
]
};
// Usage
@Injectable({ providedIn: 'root' })
export class ApiService {
private apiUrl = inject(API_URL);
getSamurai(id: number) {
return this.http.get(`${this.apiUrl}/samurai/${id}`);
}
}Provider Factories
// useFactory - dynamic value creation
{
provide: LoggerService,
useFactory: (env: EnvironmentService) => {
return env.isProduction()
? new ProductionLogger()
: new DevelopmentLogger();
},
deps: [EnvironmentService]
}
// useClass - swapping implementations
{
provide: StorageService,
useClass: environment.production
? CloudStorageService
: LocalStorageService
}
// useExisting - alias
{
provide: OldService,
useExisting: NewService
}Multi Providers
export const HTTP_INTERCEPTORS = new InjectionToken<HttpInterceptor[]>('HTTP_INTERCEPTORS');
// You can add multiple values to a single token
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: LoggingInterceptor,
multi: true
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is InjectionToken used for in Angular?
2. Which key do you use to assign a constant value to an InjectionToken in providers?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange the expression that creates an InjectionToken (one line):
- Code editor
Complete the InjectionToken for the API configuration and its use in the component.
- Horizontal ordering
Arrange the provider object that uses a factory (one line):
- Click in order
Build the flag that lets you add multiple values to a single token (one line):
- Vertical ordering
Order the registration of an InjectionToken in the application configuration (consecutive lines):