javascript / expert
Snippet
Extensible Architectures with Multi-Provider Hooks
Multi-providers allow you to define an array of services under a single InjectionToken. This pattern is vital for building plugin systems where different parts of an application can contribute functionality (like tracking or validation) without the core service needing to know about specific implementations.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
export const ANALYTICS_HOOK = new InjectionToken<AnalyticsHook[]>('Hooks');@Injectable()export class AnalyticsService {constructor(@Inject(ANALYTICS_HOOK) private hooks: AnalyticsHook[]) {}track(event: string) {this.hooks.forEach(hook => hook.execute(event));}}// Usage in Module/Component providers:// { provide: ANALYTICS_HOOK, useClass: GoogleAnalyticsHook, multi: true }
angular
Breakdown
1
new InjectionToken<AnalyticsHook[]>('Hooks')
Creates a unique identifier for the collection of hooks.
2
multi: true
Instructs Angular to accumulate providers into an array instead of overwriting.
3
this.hooks.forEach(...)
Iterates through all registered implementations dynamically.