首页 > 最新热文 > 计算机探索

依赖注入类方法AngularJS无法访问无法访问、方法、AngularJS

2023-09-14 23:10:28 作者:国民帅比

我使用ES6类角控制器和我正在与依赖注入轻微的烦恼。拿这个控制器,例如(显然不是一个真正的类)。

 类PersonController {  构造函数(MyDependency){    MyDependency.test(); //这个工程  }  的SendEvent(){    MyDependency.test(); // MyDependency是不确定的  }}。PersonController $注射= ['MyDependency'];出口默认PersonController; 

在运行构造,依赖被发现罚款。但是,如果我称之为的SendEvent 方法(或任何其他类的方法),依赖不再定义。我只需将其连接到解决此之前得到这个在构造例如 this.MyDependency = MyDependency;

有没有其他办法,这可以在不挂依赖电源来实现这个

解决方案

好像也没有其他办法可以做到这一点,所以我会坚持使用这个

I'm using ES6 classes for Angular controllers and I'm running into a slight annoyance with dependency injection. Take this controller, for example (obviously not a real class).

class PersonController {
  constructor(MyDependency) {
    MyDependency.test(); // this works
  }

  sendEvent() {
    MyDependency.test(); // MyDependency is undefined
  }
}

PersonController.$inject = ['MyDependency'];

export default PersonController;
依赖注入设计模式 angularJs

When the constructor is run, the dependency is found fine. However if I call the sendEvent method (or any other class method), the dependency is no longer defined. I've gotten around this before by just attaching it to this in the constructor e.g. this.MyDependency = MyDependency;.

Is there any other way that this can be achieved without hanging the dependency off this?

解决方案

Seems like there is no other way to do this, so I will stick to using this!

相关文章
猜你喜欢
精彩推荐