注入实现某些接口的所有服务

编程入门 行业动态 更新时间:2024-10-10 12:22:47
本文介绍了注入实现某些接口的所有服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

简单情况:

我有多个实现通用接口的服务.所有这些服务都在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

更多推荐

注入实现某些接口的所有服务

本文发布于:2023-11-06 01:59:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562432.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!