-3

So I have following piece of code:

someService.doSomething().subscribe(result=>{
   this.handleMyResult(result)
}

And I would like to do something like that:

someService.doSomething().subscribe(this.handleMyResult);

This does not work in 100%. I think that I might have some sytax issue here, as handleMyResult gets called indeed, but argument passed in is undefined

Is it possible to make it work??

Antoniossss
  • 24,977
  • 3
  • 43
  • 86
  • You said it's the argument being passed in that's undefined, but did you mean to say it was the value of `this` that's undefined? If so, have a read of [this](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) to better understand `this` and then [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) to better understand why arrow functions "fix" this. – Kirk Larkin Jan 04 '18 at 16:38
  • Its good to know that it is called "arrow functions" - didnt know that. Why does it work I can imagine cuz of my knowledge of lambads and anonymous classes in java (altough there is no `this` context in it) and closures in php – Antoniossss Jan 04 '18 at 17:28
  • And what makes me curious is why question is getting downvoted while correct answer to it gets possitive feedback – Antoniossss Jan 04 '18 at 17:29

1 Answers1

3

This works

someService.doSomething().subscribe(this.handleMyResult);

and result is passed in, but to use the this component scope within the this.handleMyResult method you must bind it.

someService.doSomething().subscribe(this.handleMyResult.bind(this));
LLai
  • 11,518
  • 2
  • 33
  • 39
  • Ok I understand, so it wont make my code more beautifull. Indeed that works like expected. Thanks! Ill accept in 5 minutes – Antoniossss Jan 04 '18 at 16:38
  • So `this.handleMyResults` equals to `MyClass.prototype.applyNewShipmentData` ahh that nasty javascript :) – Antoniossss Jan 04 '18 at 17:33