8

例:角2在组分有条件注入服务

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

    } 
} 
+1

使用'useFactory'或'injector.get' – yurzui

+0

或者可能创建DashboardComponent的特定实例。看起来奇怪这个组件是多态的,以至于使用两个服务。我可能错了,当然,因为我们错过了域的上下文 – Sebas

+0

检查这个类似的问题,我要求正确处理angular2中的IoC:http://stackoverflow.com/a/42422835/1291428 – Sebas

回答

8

可以使用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

并再次提到,你可以在其他服务中获得这些注射器和再注入该服务到您的组件。

+0

真棒。这样可行! – Ajey

+0

这是服务定位器模式;你没有注入服务。这两种服务都应注入提供者,然后将提供者注入组件。 –

+0

@MeirionHughes我在downvote之前添加了免责声明并感谢您的评论 – echonax