javascript / intermediate
Snippet
Decoupling with InjectionToken
InjectionToken is used to inject values that don't have a class type, such as configurations or API keys. This promotes loose coupling and easier testing.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
import { InjectionToken, inject } from '@angular/core';export const APP_CONFIG = new InjectionToken<string>('Config');export class LoggerService {private config = inject(APP_CONFIG);log() {console.log('Active Config:', this.config);}}
angular
Breakdown
1
export const APP_CONFIG = new InjectionToken<string>('Config');
Creates a unique token for the dependency injection system.
2
private config = inject(APP_CONFIG);
Uses the functional inject() to retrieve the value associated with the token.
3
console.log('Active Config:', this.config);
Accesses the injected configuration value inside a method.