Injected dependencies not accessible in class methods for AngularJS

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?

Answers:

Answer

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.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.