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
?
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:-
Another ways to emulate private properties are :- using Symbols/weakmaps or creating a closure around the whole class and store MyDependency within this closure.
Seems like there is no other way to do this, so I will stick to using
this
!