Angular 2有条件地在组件中注入服务

Aje*_*jey 13 javascript dependency-injection angular2-services angular

例如:

我有2项服务

1)one.service.ts

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

    }
}
Run Code Online (Sandbox Code Playgroud)

eko*_*eko 17

你可以使用 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

正如@MeirionHughes所提到的,这被称为服务定位器模式:

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

除非你真的需要它,否则避免使用这种技术.它鼓励像你在这里看到的粗心的抓包方法.很难解释,理解和测试.您无法通过检查构造函数来了解此类需要什么或将执行什么操作.它可以从任何祖先组件获取服务,而不仅仅是它自己的组件.您不得不通过实施来发现它的作用.

框架开发人员在必须一般性地动态获取服务时可以采用这种方法.

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

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