Simple scenario:
I have multiple Services that implement a common Interface. All those Services are registered within the bootstrap
method.
Now I'd like to have another Service, which injects all registered Services that implement the common Interface.
i.e.
export interface MyInterface {
foo(): void;
}
export class Service1 implements MyInterface {
foo() { console.out("bar"); }
}
export class Service2 implements MyInterface {
foo() { console.out("baz"); }
}
export class CollectorService {
constructor(services:MyInterface[]) {
services.forEach(s => s.foo());
}
}
Is that possible somehow?
Because interfaces are not available at runtime (only for static checks) interfaces can't be used as toke for DI.
Use a token instead:
(deprecated)
https://angular.io/api/core/OpaqueTokenhttps://angular.io/api/core/InjectionToken
You need to register your service providers like this:
This will work only with classes not with interfaces since interfaces don't exist at runtime.
To make it work with interfaces, you need to adapt it:
and inject this way:
See this plunkr for more details: https://plnkr.co/edit/HSqOEN?p=preview.
See this link for more details: