Injected dependencies not accessible in class meth

2019-05-19 03:49发布

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?

2条回答
我命由我不由天
2楼-- · 2019-05-19 03:53

It is because myDependency is not accessible in your methods. Do this.myDependency = myDependency in the constructor and then do this.my dependency.test() in your method.

EDIT: Below is an alternative approach:-

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

sendEvent() {
    _myDependency.test(); // this will work
  }
}

Another ways to emulate private properties are :- using Symbols/weakmaps or creating a closure around the whole class and store MyDependency within this closure.

查看更多
▲ chillily
3楼-- · 2019-05-19 03:56

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

查看更多
登录 后发表回答