Angular 如何有条件地将服务注入组件?

Angular 如何有条件地将服务注入组件?,angular,dependency-injection,angular2-services,Angular,Dependency Injection,Angular2 Services,我有两个服务1.service.ts和2.service.ts,还有一个组件dashboard.component.ts 如何有条件地将这些服务注入组件 import { Component, ViewEncapsulation, Inject } from '@angular/core'; import { OneService } from '../services/one.service'; import { TwoService } from '../services/two.servi

我有两个服务
1.service.ts
2.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 */    
         }

    }
}

您可以使用
喷油器

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);
  }
}
从'@angular/core'导入{Injector}
...
构造函数(专用注入器:注入器){
如果(真){
this.oneService=this.injector.get(oneService);
}否则{
this.twoService=this.injector.get(twoService);
}
}
正如@MeirionHughes所提到的,这被称为服务定位器模式:

该技术是服务定位器模式的一个示例

除非您真正需要,否则请避免使用此技巧。它鼓励了一种粗心的抓包方法,就像你在这里看到的那样。很难解释、理解和测试。通过检查构造函数,您无法知道这个类需要什么或它将做什么。它可以从任何祖先组件获取服务,而不仅仅是它自己的。您必须探索实现以发现它的功能

当框架开发人员必须以通用和动态的方式获取服务时,他们可以采用这种方法

资料来源:


同样,如前所述,您可以在另一个服务中获取这些注入器,然后将此服务注入您的组件。

使用
useFactory
injector。获取
或创建仪表板组件的特定实例。这个组件如此多态,以至于使用了两个服务,这似乎很奇怪。当然,我可能错了,因为我们错过了域上下文对不起,这是一个糟糕的做法,你打破了国际奥委会的模式,这是你首先拥有(可注入)服务的唯一原因。答案在技术上是很好的(我从中学到了),但我必须投反对票。我已经取消了我的反对票(至少作为最后手段是有用的),但我建议人们找一个提供者/建设者/工厂/门面,避免使用注入器。get()