Angular 2 dynamic dependency injection based on @Input()

前端 未结 4 995
长发绾君心
长发绾君心 2020-12-25 13:18

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

I want to write someth

4条回答
  •  执念已碎
    2020-12-25 14:08

    It is

    // 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(trendyServiceMap[this.use]);
        } else {
            throw new Error(`There's no such thing as '${this.use}'`);
        }
    }
    

提交回复
热议问题