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

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


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


This is related to the fat arrow behavior.

You can find more here (in the "this and fat arrow" topic, about half the page)