We use cookies to enhance your experience on the site
CodeWorlds

Injection Tokens and Advanced DI

Injection Tokens

Tokens allow injecting values other than classes:

1import { InjectionToken, inject } from '@angular/core';
2
3// Token definition
4export const API_URL = new InjectionToken<string>('API_URL');
5export const FEATURE_FLAGS = new InjectionToken<FeatureFlags>('FEATURE_FLAGS');
6
7// Registration in configuration
8export const appConfig: ApplicationConfig = {
9  providers: [
10    { provide: API_URL, useValue: 'https://api.dojo.com/v1' },
11    {
12      provide: FEATURE_FLAGS,
13      useValue: {
14        darkMode: true,
15        newDashboard: false
16      }
17    }
18  ]
19};
20
21// Usage
22@Injectable({ providedIn: 'root' })
23export class ApiService {
24  private apiUrl = inject(API_URL);
25
26  getSamurai(id: number) {
27    return this.http.get(\`\${this.apiUrl}/samurai/\${id}\`);
28  }
29}

Provider Factories

1// useFactory - dynamic value creation
2{
3  provide: LoggerService,
4  useFactory: (env: EnvironmentService) => {
5    return env.isProduction()
6      ? new ProductionLogger()
7      : new DevelopmentLogger();
8  },
9  deps: [EnvironmentService]
10}
11
12// useClass - swapping implementations
13{
14  provide: StorageService,
15  useClass: environment.production
16    ? CloudStorageService
17    : LocalStorageService
18}
19
20// useExisting - alias
21{
22  provide: OldService,
23  useExisting: NewService
24}

Multi Providers

1export const HTTP_INTERCEPTORS = new InjectionToken<HttpInterceptor[]>('HTTP_INTERCEPTORS');
2
3// You can add multiple values to a single token
4{
5  provide: HTTP_INTERCEPTORS,
6  useClass: AuthInterceptor,
7  multi: true
8},
9{
10  provide: HTTP_INTERCEPTORS,
11  useClass: LoggingInterceptor,
12  multi: true
13}
Go to CodeWorlds