Angular 2 dynamic dependency injection based on @Input()

前端 未结 4 996
长发绾君心
长发绾君心 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:07

    I would like to take Estus Flask answer a step further and create a logic that imports the service rather than having to declare the names as array objects.

    Basically, we just have to pass in the path and name of the service and the rest is almost the same.

    public _dynamicService: any;
    
    dynamicDI(service_path, service_name){
        import(service_path).then(s => {
    
          this._dynamicService = this.injector.get(s['service_name']);
    
        })
    }
    

    Now, you can access the functions inside the dynamicService as follows:

    (Let's assume we have a http observable fn in the service we need)

    this._dynamicService['your_function_name']().subscribe(res=> { console.log(res) } );
    

提交回复
热议问题