If you're working in your app.module
, you have the option to utilize a string value:
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ],
providers: [
MyPipe,
{ provide: 'myPipe', useClass: MyPipe }
]
})
export class AppModule { }
Subsequently, you can inject this string into your component accordingly:
import { Component, Injector } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
constructor(private injector:Injector){
var myInterface = injector.get('myPipe');
myInterface.transform('test');
}
}
For a visual reference, here's a StackBlitz example.
UPDATE
To eliminate the deprecated use of injector.get
while retaining the ability to access the service with a string parameter, employing a service to determine the appropriate injection token is an alternative solution.
Begin by establishing a Service for mapping strings to respective injection tokens:
@Injectable()
export class TokenService {
static MY_PIPE_TOKEN = new InjectionToken<MyPipe>('myPipe');
getToken(name: string): InjectionToken<any> {
if (name === 'myPipe') {
return TokenService.MY_PIPE_TOKEN;
} else {
throw `No token with name ${name} found`;
}
}
}
Follow up by configuring your providers using the Injection Token provided by the Service:
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ],
providers: [
TokenService,
MyPipe,
{ provide: TokenService.MY_PIPE_TOKEN, useClass: MyPipe }
]
})
export class AppModule { }
In your component, utilize the service to retrieve the correct token:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
constructor(private injector:Injector, private tokenService: TokenService){
let myInterface = injector.get(tokenService.getToken('myPipe'));
myInterface.transform('test');
}
}
A relevant updated example can be viewed via StackBlitz.