【发布时间】:2017-09-12 23:58:49
【问题描述】:
我有两个服务one.service.ts 和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 */
}
}
}
【问题讨论】:
-
使用
useFactory或injector.get -
或者创建 DashboardComponent 的特定实例。这个组件多态到使用两个服务的地步,这似乎很奇怪。当然,我可能错了,因为我们错过了域上下文
标签: angular dependency-injection angular2-services