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?
this. This is straightforward and common way to save some arguments from constructorthisand I have every time I've had to do this, I was just wondering if there was any other 'accepted' way to do it.