Pet*_*ser 3 strategy-pattern service-locator angular
在我的Angular(4+)应用程序中,我想创建一个基本的插件机制:
示例:SearchStrategy与实现的接口PersonSearchStrategy和DocumentSearchStrategy(两个服务,注册为提供者).
有没有办法通过查询SearchStrategy接口的实现来动态获取这些服务的实例?怎么样?
(可能是一些与注射器相关的功能?)
如果您注册服务InjectionToken并使用提供,则有可能提供multi.
您可以使用接口创建注入令牌.
export const SearchStrategyToken = new InjectionToken<SearchStrategy[]>('SearchStrategy');
Run Code Online (Sandbox Code Playgroud)
在您的模块寄存器中:
providers: [
{provide: SearchStrategyToken, useClass: PersonSearchStrategy, multi: true},
{provide: SearchStrategyToken, useClass: DocumentSearchStrategy, multi: true},
]
Run Code Online (Sandbox Code Playgroud)
在您的组件或服务中:
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');
}
Run Code Online (Sandbox Code Playgroud)
此处提供的代码示例:https://stackblitz.com/edit/angular-clxr6k.
但是,如果您提供有关用例的更多详细信息,那将是一件好事.可能有比上述路线更好的解决方案.
| 归档时间: |
|
| 查看次数: |
932 次 |
| 最近记录: |