gpt4 book ai didi

Angular 2 基于@Input() 的动态依赖注入(inject)

转载 作者:太空狗 更新时间:2023-10-29 16:55:15 24 4
gpt4 key购买 nike

假设我有一个 Angular 2 组件指令,我希望组件使用的注入(inject)依赖项由 @Input() 确定。

我想写类似 <trendy-directive use="'serviceA'"> 的东西并让 TrendyDirective 的实例使用 serviceA,或者如果这是我指定的,则让它使用 serviceB。 (这是我实际尝试做的过于简单化的版本)

(如果您认为这是一个糟糕的想法,我愿意接受您的反馈,但请解释原因。)

这是一个如何实现我的想法的例子。在此示例中,假设 ServiceA 和 ServiceB 是可注入(inject)的,它们都通过具有“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();
}
}

我认为这在技术上可行,但必须有更好的方法来进行动态依赖注入(inject)。

最佳答案

// can be a service also for overriding and testing
export const trendyServiceMap = {
serviceA: ServiceA,
serviceB: ServiceB
}

constructor(private injector: Injector) {}
...
ngOnInit() {
if (trendyServiceMap.hasOwnProperty(this.use)) {
this.service = this.injector.get<any>(trendyServiceMap[this.use]);
} else {
throw new Error(`There's no such thing as '${this.use}'`);
}
}

关于Angular 2 基于@Input() 的动态依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41366108/

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