依赖注入类方法AngularJS无法访问 [英] Injected dependencies not accessible in class methods for AngularJS

查看:148
本文介绍了依赖注入类方法AngularJS无法访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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


解决方案

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

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;

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!

这篇关于依赖注入类方法AngularJS无法访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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