angular - 如何有条件地将服务注入(inject)组件?

标签 angular dependency-injection angular2-services

我有 2 个服务 one.service.tstwo.service.ts,以及一个组件 dashboard.component.ts

如何有条件地将那些服务注入(inject)到组件中?

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 提到的,这称为服务定位器模式:

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.

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

再次如前所述,您可以在另一个服务中获取这些注入(inject)器,然后将此服务注入(inject)到您的组件中。

关于angular - 如何有条件地将服务注入(inject)组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43450259/

相关文章:

java - 将 guice 与自定义数据源一起使用

java - SEAM:如何在动态加载的类中获取EntityManager和Logger?

Angular2 http 获取返回字符串的问题

angular - 你可以使用 @ViewChild() 或类似的路由器 socket 吗?如果是这样怎么办?

javascript - Angular 2 _this 未定义

angular - 将力矩导入 Angular 会出错

Angular 6 和 Electron : Using a mocked class for unit testing and extend the real class does not work

c# - 如何在 .NET Core 控制台应用程序中处理 Scoped 服务实例?

angular - @Input 是否提供双向绑定(bind)?

javascript - 如何拦截提交表单?