gpt4 book ai didi

angular - 如何有条件地将服务注入(inject)组件?

转载 作者:可可西里 更新时间:2023-11-01 02:05:22 25 4
gpt4 key购买 nike

我有 2 个服务 one.service.tstwo.service.ts,以及一个组件 dashboard.component.ts

如何有条件地将那些服务注入(inject)到组件中?

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

The technique is an example of the service locator pattern.

Avoid this technique unless you genuinely need it. It encourages a careless grab-bag approach such as you see here. It's difficult to explain, understand, and test. You can't know by inspecting the constructor what this class requires or what it will do. It could acquire services from any ancestor component, not just its own. You're forced to spelunk the implementation to discover what it does.

Framework developers may take this approach when they must acquire services generically and dynamically.

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

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

关于angular - 如何有条件地将服务注入(inject)组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43450259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com