angular2 +在param上创建动态提供者服务

时间:2017-11-07 02:06:22

标签: angular

作为下面的plunker,我希望通过useFactory创建动态提供程序,例如'TestService'。如果param是'A',那么提供者应该是'TestServiceA',如果params是'B',那么提供者应该是'TestServiceB'

怎么做?感谢

https://plnkr.co/edit/8JDopoVCmKSPaQxk0iJH?p=preview

export class App {
  type: string = 'A';  

  text:string;
  constructor(
    @Inject('TestService') private testService
  ) {
    this.text = this.testService.test();
  }
}

1 个答案:

答案 0 :(得分:0)

您可以从工厂返回功能

export function testServiceFactory2() {
  return (serviceType) => {
    return serviceType === 'A' 
      ? new TestServiceA()
      : new TestServiceB()
  }
}

并像这样使用

providers: [
  {provide: 'TestService', useFactory: testServiceFactory2}
]


constructor(@Inject('TestService') private testService) {
  // this.text = this.testService.test();
  this.text = this.testService(this.type).test();
}