Multi-Providers with Injection Tokens
Display how to use Angular's multi-provider option to associate multiple values with a single InjectionToken.
import { InjectionToken } from '@angular/core';
// Define a new injection token for use with multi-providers
export const MULTI_TOKEN = new InjectionToken<string[]>('multi.token');
This piece of code creates a new InjectionToken that can hold an array of strings. This token will be used to inject multiple values with the same token.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MULTI_TOKEN } from './path-to-token-definition';
@NgModule({
declarations: [],
imports: [CommonModule],
providers: [
{ provide: MULTI_TOKEN, useValue: 'Value 1', multi: true },
{ provide: MULTI_TOKEN, useValue: 'Value 2', multi: true },
{ provide: MULTI_TOKEN, useValue: 'Value 3', multi: true }
]
})
export class SomeModule { }
Here, a module is defined where the MULTI_TOKEN is provided with multiple string values. The 'multi: true' property is what allows us to associate multiple values with a single InjectionToken.
import { Component, Inject } from '@angular/core';
import { MULTI_TOKEN } from './path-to-token-definition';
@Component({
selector: 'app-multi-provider-component',
template: `<ul><li *ngFor="let value of values">{{ value }}</li></ul>`
})
export class MultiProviderComponent {
constructor(@Inject(MULTI_TOKEN) public values: string[]) {}
}
In this component, we are injecting the array of values associated with MULTI_TOKEN and iterating over them using an *ngFor loop to display each one in a list item.