假设我有一个Angular 2组件指令,其中我希望组件使用的注入依赖由@Input()确定。基于@Input的角度2动态依赖注入()
我想写一些类似<trendy-directive use="'serviceA'">
的东西,并让TrendyDirective的实例使用serviceA,或者让它使用serviceB(如果这是我指定的)。 (这是什么实际上,我试图做一个过于简化版本)
(如果你认为这是一开始就有一个可怕的想法,我接受这些反馈,但请解释原因。)
下面是如何实现我所想的一个例子。在这个例子中,假设ServiceA和ServiceB是通过具有'superCoolFunction'来实现iService的注入。
@Component({
selector: 'trendy-directive',
...
})
export class TrendyDirective implements OnInit {
constructor(
private serviceA: ServiceA,
private serviceB: ServiceB){}
private service: iService;
@Input() use: string;
ngOnInit() {
switch (this.use){
case: 'serviceA': this.service = this.serviceA; break;
case: 'serviceB': this.service = this.serviceB; break;
default: throw "There's no such thing as a " + this.use + '!';
}
this.service.superCoolFunction();
}
}
我认为这在技术上是可行的,但是有一个更好的方法来做动态依赖注入。
由于4.0'get'已被弃用。 –
我的意思是签名。请参阅https://github.com/angular/angular/blob/5.2.5/packages/core/src/di/injector.ts#L62 –
使用类型调用泛型方法总是更好。我不确定这个签名是否会被删除。它可以让用户知道使用泛型更好。无论如何,我更新了答案,感谢您的关注。通常我不打扰彻底输入解决方案,并专注于提供它的要点。 – estus