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()
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With