2

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?

3
  • If you only can inject it into instances, then no there is no way around that. Commented May 24, 2015 at 10:23
  • Why are you afraid of using this. This is straightforward and common way to save some arguments from constructor Commented May 24, 2015 at 21:17
  • @just-boris I have no issue with using this and I have every time I've had to do this, I was just wondering if there was any other 'accepted' way to do it. Commented May 25, 2015 at 1:53

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, was too quick to answer. Didn't see that you are asking for an alternative to this approach
Using global variable is not good idea to expose injectables. It will be rewritten with every call of constructor
True but also depends on what kind of value you are storing. For something like http, if you dont want it to be attached to this, there is no problem in thus approach. It won't pollute the global scope as it is in an ES6 module. As I also mentioned, another approach is to use symbols/weakmaps.
Adding to my previous comment, personally I don't think there is anything particularly wrong in attaching the dependency to this.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.