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