基于@Input()的Angular 2动态依赖注入 [英] Angular 2 dynamic dependency injection based on @Input()

查看:98
本文介绍了基于@Input()的Angular 2动态依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have an Angular 2 component-directive, where I want the injected dependency that the component uses to be determined by an @Input().

我想编写类似<trendy-directive use="'serviceA'">的东西,并让TrendyDirective的实例使用serviceA,或者如果我指定的话,使其使用serviceB. (这是我实际上想做的事情的简化版)

I want to write something like <trendy-directive use="'serviceA'"> and have that instance of TrendyDirective use serviceA, or have it use serviceB if that's what I specify. (this is an oversimplified version of what I'm actually trying to do)

(如果您以为这是一个糟糕的主意,我欢迎您提供反馈意见,但请解释原因.)

(If you think this is a terrible idea to begin with, I'm open to that feedback, but please explain why.)

这里是如何实现我所想的一个例子.在此示例中,假设ServiceA和ServiceB是可注射的,并且都通过具有"superCoolFunction"来实现iService.

Here's one example of how to achieve what I'm thinking of. In this example, imagine that ServiceA and ServiceB are injectables that both implement iService by having a 'superCoolFunction'.

@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();
    }
}

我认为这在技术上是可行的,但是必须有一种更好的方法来进行动态依赖注入.

I think this technically would work, but there's got to be a better way to do dynamic dependency injection.

推荐答案

// 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}'`);
    }
}

这篇关于基于@Input()的Angular 2动态依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆