简体   繁体   English

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

[英]How to conditionally inject service into component?

I have 2 services one.service.ts and two.service.ts , and a component dashboard.component.ts .我有 2 个服务one.service.tstwo.service.ts ,以及一个组件dashboard.component.ts

How to conditionally inject those service into the component?如何有条件地将这些服务注入到组件中?

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 */    
         }

    }
}

You can use the Injector您可以使用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);
  }
}

As @MeirionHughes mentioned this is called the service locator pattern:正如@MeirionHughes 提到的,这被称为服务定位器模式:

The technique is an example of the service locator pattern.该技术是服务定位器模式的一个示例。

Avoid this technique unless you genuinely need it.除非您真的需要,否则请避免使用此技术。 It encourages a careless grab-bag approach such as you see here.它鼓励像你在这里看到的那样粗心大意的抓包方法。 It's difficult to explain, understand, and test.很难解释、理解和测试。 You can't know by inspecting the constructor what this class requires or what it will do.通过检查构造函数,您无法知道此类需要什么或它将做什么。 It could acquire services from any ancestor component, not just its own.它可以从任何祖先组件获取服务,而不仅仅是它自己的。 You're forced to spelunk the implementation to discover what it does.您被迫深入研究实现以发现它的作用。

Framework developers may take this approach when they must acquire services generically and dynamically.当框架开发人员必须通用和动态地获取服务时,他们可能会采用这种方法。

Source: https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#explicit-injector来源: https : //angular.io/docs/ts/latest/guide/dependency-injection.html#!#explicit-injector

And again as mentioned you can get these injectors in another service and then inject this service into your component.如前所述,您可以在另一个服务中获取这些注入器,然后将该服务注入到您的组件中。

In other words you want to achieve Bridge or Abstract Factory pattern.换句话说,您要实现BridgeAbstract Factory模式。 In this case you can use useFactory .在这种情况下,您可以使用useFactory Related post .相关帖子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM