I'm learning Angular2 with Typescript and I have a problem.
I have two classe that imprements same interface. How can I inject them to a service as a list ?
I read about opaquetoken https://angular.io/docs/ts/latest/guide/dependency-injection.html#opaquetoken
But I don't know if I need to use it and how to use it.
export interface CheckerInterface {
check(text : string) : boolean
}
export class Checker1 implements CheckerInterface {
check(text : string) : boolean {
//do something
return true;
}
export class Checker2 implements CheckerInterface {
check(text : string) : boolean {
//do something
return true;
}
@Injectable()
export class Service {
constructor(private checkers: CheckerInterface[]) { //??
checkers.foreach( checker => checker.check(somestring));
}
}
Thanks for any help !
You need to either add the array as a provider, or use
multi: true
in theprovider
configuration.Or
The second one is probably preferable, as you let Angular create them, allowing them to be injected with their own dependencies if needed.
Then you just need to use the
CHECKERS
token when you inject