ES6类中使用Angular 1 DI的问题

ES6 classes with Angular 1 DI issue with $inject

本文关键字:DI 问题 Angular ES6      更新时间:2023-09-26
class Foo {
    constructor(dep1) {
    }
}
Foo.$inject = ['Dependency1']

我知道你可以在angular/wes6类中这样做。然而,我还需要传递一些东西到我的构造函数foo(一个配置对象)。这让我很困惑,因为据我所知,DI参数是优先的。

实际上,我想做

let foo = new Foo(config); //config defined above

方案一:

let angular = window.angular;
class Foo{
    constructor(config){
        let injector = angular.injector();
        let dep1 = injector.get('Dependency1');
        this.prop1 = config.prop;
        this.prop2 = dep1.get(); 
    }
}

解决方案2:

//assuming ES6 modules, export dependency as module
import dependency from 'path';
class Foo{
    constructor(config){
        this.prop1 = config.prop;
        this.prop2 = dependency.get();
    }
}