Angular: 查找所有实现特定接口的提供者

Angular: lookup all providers implementing a specific interface

在我的 Angular (4+) 应用程序中,我想创建一个基本的插件机制:

示例:接口 SearchStrategy 实现 PersonSearchStrategyDocumentSearchStrategy(两种服务,注册为提供者)。

有没有办法通过查询 SearchStrategy 接口的实现来动态获取这些服务的实例? 怎么做?

(可能是一些 Injector 相关的功能?)

这是有可能的,前提是您使用 InjectionToken 注册服务并使用 provide multi.

您可以创建带有接口的注入令牌。

export const SearchStrategyToken = new InjectionToken<SearchStrategy[]>('SearchStrategy');

在您的模块寄存器中:

providers: [
  {provide: SearchStrategyToken, useClass: PersonSearchStrategy, multi: true}, 
  {provide: SearchStrategyToken, useClass: DocumentSearchStrategy, multi: true},
]

在您的组件或服务中:

constructor(private injector: Injector) {

  const services = this.injector
  .get(SearchStrategyToken); // return 2 items [ PersonSearchStrategy, DocumentSearchStrategy ]

  const personSearch = services.find(x => x.constructor.name === 'PersonSearchStrategy');

  const docSearch = services.find(x => x.constructor.name === 'DocumentSearchStrategy');

}

此处提供的代码示例:https://stackblitz.com/edit/angular-clxr6k

但是,如果您提供有关您的用例的更多详细信息,那将是很好的。可能有比上述路线更好的解决方案。