Currently, I am diving deep into the world of rxjs Observables, Observers, and Subscriptions. In order to grasp their functionality better, I decided to experiment with a sample code that updates the UI with random numbers at intervals of 1 second. My ultimate aim is to figure out how to update multiple components using a single observable. However, I encountered an obstacle when trying to update a component variable with the next observer from the subscription. Here's a snippet of my code:
When I try to enable this.updateNumber(num)
, it throws an error saying the method is not available. I suspect the issue lies with the this
keyword. How can I reference class variables and methods from within the next()
function?
this.number1 = 0;
clickSix() {
this.number1 = 1;
const randomGeneratorOnIntervalObservable = new Observable(
this.obsCheckService.randomGeneratorOnIntervalSubscription
);
randomGeneratorOnIntervalObservable.subscribe({
next(num) {
console.log(num);
// this.updateNumber(num);
this.number1 = num;
},
complete() {
console.log('Finished sequence');
},
});
this.number1 = 2;
}
updateNumber(num: number) {
this.number1 = num;
}