gpt4 book ai didi

angular - 注入(inject)实现某些接口(interface)的所有服务

转载 作者:太空狗 更新时间:2023-10-29 17:04:41 26 4
gpt4 key购买 nike

简单场景:

我有多个实现通用接口(interface)的服务。所有这些服务都在 bootstrap 方法中注册。

现在我想要另一个服务,它注入(inject)所有实现公共(public)接口(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());
}
}

这有可能吗?

最佳答案

您需要像这样注册您的服务提供商:

boostrap(AppComponent, [
provide(MyInterface, { useClass: Service1, multi:true });
provide(MyInterface, { useClass: Service2, multi:true });
]);

这仅适用于类而不适用于接口(interface),因为接口(interface)在运行时不存在。

要使其与接口(interface)一起工作,您需要对其进行调整:

bootstrap(AppComponent, [
provide('MyInterface', { useClass: Service1, multi:true }),
provide('MyInterface', { useClass: Service2, multi:true }),
CollectorService
]);

并以这种方式注入(inject):

@Injectable()
export class CollectorService {
constructor(@Inject('MyInterface') services:MyInterface[]) {
services.forEach(s => s.foo());
}
}

有关详细信息,请参阅此插件:https://plnkr.co/edit/HSqOEN?p=preview .

有关详细信息,请参阅此链接:

关于angular - 注入(inject)实现某些接口(interface)的所有服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35916542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com