0

I am using Rx with Angular2, and using the Subscribe method, the call backs of the method preserve context of the component (or class) that called it, without passing any reference to it. My question is how do they do that? What is the Javascript trick that makes it possible?

Code snippet:

this._userService.SignUpUser(this.model).subscribe(
     user => {
       this.newuser = user; // this, is actually same as the calling "this"? How does this work?      
       },
       error => this.errorMessage = <any>error  
);   
Ayyash
  • 4,257
  • 9
  • 39
  • 58
  • I don't think it is a duplicate, I have been searching for three hours, I had no idea the answer lied in arrow functions, so I really advice against marking it as duplicate – Ayyash Apr 19 '16 at 12:35

2 Answers2

4

It's because of the use of an arrow function that provides lexical this keyword. In this case, this doesn't correspond to the instance that executes the function but the instance where the function is defined.

It's not related to Rx at all.

See this link for more details:

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
3

It is because of => instead of function()

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567