簡體   English   中英

如何有條件地將服務注入組件?

[英]How to conditionally inject service into component?

我有 2 個服務one.service.tstwo.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 */    
         }

    }
}

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

如前所述,您可以在另一個服務中獲取這些注入器,然后將該服務注入到您的組件中。

換句話說,您要實現BridgeAbstract Factory模式。 在這種情況下,您可以使用useFactory 相關帖子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM