[SOLVED] rxjs subscription issue while updating the component UI

Issue

This Content is from Stack Overflow. Question asked by Ketan Bhavsar

I am currently working on understanding the rxjs Observable, Observer and Subscription.
To understand the same I wrote a sample code for updating UI with the random numbers with the interval of 1 second. My goal is to work on updating the multiple components from a single observable. But I stuck at the point where a component variable is not updating with the subscription’s next observer. My code is as below,

https://stackblitz.com/edit/angular-ivy-z11va4?file=src/app/app.component.ts

when I enable this.updateNumber(num) it says method is not available. I believe issue is with this key word. How to reference class variable and methods from next()?

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;
      }



Solution

use arrow function to solve this problem:

randomGeneratorOnIntervalObservable.subscribe(
    (num) => {
        console.log(num);
        this.updateNumber(num);
        this.number1 = num;
    },
    (error) => {
        console.log(error);
    },
    (complete) => {
        console.log('Finished sequence');
    });
  this.number1 = 2;
}

Update:

randomGeneratorOnIntervalObservable.subscribe({
     next: (num: number) => {
        console.log(num);
        this.updateNumber(num);
        this.number1 = num;
    },
     error: (error: Error) => {
        console.log(error);
    },
    complete: () => {
        console.log('Finished sequence');
    }});
  this.number1 = 2;
}

Note: Unlike regular functions, arrow functions do not have their own this. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

Reference Documentation
https://betterprogramming.pub/difference-between-regular-functions-and-arrow-functions-f65639aba256


This Question was asked in StackOverflow by Ketan Bhavsar and Answered by Arman Ashoori It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?