[英]How to conditionally inject service into component?
我有 2 个服务one.service.ts
和two.service.ts
,以及一个组件dashboard.component.ts
。
如何有条件地将这些服务注入到组件中?
import { Component, ViewEncapsulation, Inject } from '@angular/core';
import { OneService } from '../services/one.service';
import { TwoService } from '../services/two.service';
@Component({
selector: 'dashboard',
encapsulation: ViewEncapsulation.Emulated,
styleUrls: ['./dashboard.less'],
templateUrl: './dashboard.html'
})
export class DashboardComponent {
constructor() {
// Here how do I get service instance based on some this condition.
if(true) {
/* Service **one.service.ts** to be injected */
} else {
/* Service **two.service.ts** to be injected */
}
}
}
您可以使用Injector
import { Injector } from '@angular/core'
...
constructor(private injector: Injector){
if(true) {
this.oneService = <OneService>this.injector.get(OneService);
} else {
this.twoService = <TwoService>this.injector.get(TwoService);
}
}
正如@MeirionHughes 提到的,这被称为服务定位器模式:
该技术是服务定位器模式的一个示例。
除非您真的需要,否则请避免使用此技术。 它鼓励像你在这里看到的那样粗心大意的抓包方法。 很难解释、理解和测试。 通过检查构造函数,您无法知道此类需要什么或它将做什么。 它可以从任何祖先组件获取服务,而不仅仅是它自己的。 您被迫深入研究实现以发现它的作用。
当框架开发人员必须通用和动态地获取服务时,他们可能会采用这种方法。
来源: https : //angular.io/docs/ts/latest/guide/dependency-injection.html#!#explicit-injector
如前所述,您可以在另一个服务中获取这些注入器,然后将该服务注入到您的组件中。
换句话说,您要实现Bridge
或Abstract Factory
模式。 在这种情况下,您可以使用useFactory
。 相关帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.