Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind this to a function for AngularIO's Observable::subscribe?

There are a lot of examples using the Observable.subscribe() function from AngularIO. Anyhow, I was only able to see anonymous functions inside as in:

bar().subscribe(data => this.data = data, ...);

If I try to hand in a function of the same class like here:

updateData(myData : DataType[]) {
   this.data = data;
}
...
bar().subscribe(this.updateData, ...);

Then the this object in line 2 doesn't refer to the current object anymore. This is probably some JavaScript logic that I don't understand. I know that you can bind an object to a function, is this what I have to do? Is this best practice? How would one usually resolve this issue (I'd like to avoid having a big anonymous function inside the subscribe().

like image 736
user2084865 Avatar asked Jun 16 '17 08:06

user2084865


1 Answers

You can wrap it inside an arrow function which will capture the correct this:

bar().subscribe((myData) => this.updateData(myData), ...);

Or use Function.bind which will also bind the correct context:

bar().subscribe(this.updateData.bind(this), ...);

But be aware that Function.bind returns any which will make you lose type checking in TypeScript. See https://github.com/Microsoft/TypeScript/issues/212

like image 145
Saravana Avatar answered Sep 20 '22 20:09

Saravana