简单情况:
我有多个实现通用接口的服务.所有这些服务都在bootstrap方法中注册.
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.
即
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()); } }有可能吗?
推荐答案您需要这样注册您的服务提供商:
You need to register your service providers like this:
boostrap(AppComponent, [ provide(MyInterface, { useClass: Service1, multi:true }); provide(MyInterface, { useClass: Service2, multi:true }); ]);这仅适用于没有接口的类,因为接口在运行时不存在.
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:
bootstrap(AppComponent, [ provide('MyInterface', { useClass: Service1, multi:true }), provide('MyInterface', { useClass: Service2, multi:true }), CollectorService ]);并以这种方式注入:
@Injectable() export class CollectorService { constructor(@Inject('MyInterface') services:MyInterface[]) { services.forEach(s => s.foo()); } }有关更多详细信息,请参见此plunkr: plnkr.co/edit/HSqOEN?p =预览.
See this plunkr for more details: plnkr.co/edit/HSqOEN?p=preview.
有关更多详细信息,请参见此链接:
See this link for more details:
- blog. Thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html
更多推荐
注入实现某些接口的所有服务
发布评论