如何有条件地将服务注入组件?

2024-02-14

我有2个服务one.service.ts and 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 */    
         }

    }
}

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

该技术是服务定位器模式的一个示例。

Avoid除非你真正需要它,否则这种技术。它鼓励了一种粗心的抓包方法,就像你在这里看到的那样。解释、理解和测试都很困难。您无法通过检查构造函数知道该类需要什么或它将做什么。它可以从任何祖先组件获取服务,而不仅仅是它自己的组件。您被迫深入了解其实现以发现它的作用。

当框架开发人员必须通用且动态地获取服务时,他们可以采用这种方法。

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何有条件地将服务注入组件? 的相关文章

随机推荐