javascript / expert
Snippet
Extensible Architectures with Multi-Provider Injection Tokens
The 'multi: true' provider strategy allows multiple values to be associated with a single InjectionToken. This is essential for plugin-based architectures where different modules contribute their own implementations (e.g., validators, interceptors, or analytics handlers) to a global registry.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export const ANALYTICS_HANDLER = new InjectionToken<AnalyticsHandler[]>('Handlers');@Injectable()export class GoogleAnalytics implements AnalyticsHandler {log(event: string) { /* ... */ }}@Component({providers: [{ provide: ANALYTICS_HANDLER, useClass: GoogleAnalytics, multi: true }]})export class AppComponent {private handlers = inject(ANALYTICS_HANDLER);track(event: string) {this.handlers.forEach(h => h.log(event));}}
angular
Breakdown
1
new InjectionToken<AnalyticsHandler[]>('Handlers');
Defines a unique token that can represent an array of implementations rather than a single instance.
2
{ provide: ANALYTICS_HANDLER, useClass: GoogleAnalytics, multi: true }
Registers a class to the token without overwriting existing providers, thanks to the 'multi' flag.
3
private handlers = inject(ANALYTICS_HANDLER);
Injects an array containing all instances registered under this token across the DI hierarchy.