Troubleshooting problem with rxjs subscription impacting component UI refresh

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:

Check out my code here

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

Answer №1

Utilize arrow functions to resolve this issue:

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

Modification:

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 possess their own this. The value of this within an arrow function remains consistent throughout its existence and is always tied to the value of this in the nearest non-arrow parent function.

For further information, refer to the documentation at

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for utilizing an alias at the top within a subquery?

Is it possible to use an alias from the top query in a subquery? I am currently encountering an error with 'artc'. let myQuery = this.articles.createQueryBuilder('artc') .select(['artc.title']) .addSelect(qb => ...

Leveraging NestJs Libraries within Your Nx Monorepo Main Application

I am currently part of a collaborative Nx monorepo workspace. The setup of the workspace looks something like this: https://i.stack.imgur.com/zenPw.png Within the structure, the api functions as a NestJS application while the data-access-scripts-execute ...

Angular 16 brings a revolution in routerLink behavior

Previously, when I was using angular < 16, my routes configuration looked like this: { path: Section.Security, canActivate: [AuthGuard, AccessGuard, AdminGuard], children: [ { path: '', pathMatch: 'full', ...

Troubleshooting the ReferenceError: Blob is not defined problem with the heic2any library in a Next.js application

Currently, I am encountering an issue where everything is properly implemented and functioning smoothly. However, the main problem arises when I attempt to reload the page, as it results in an error message: ReferenceError: Blob is not defined. This issue ...

What is the process for displaying data within an Angular 10 component?

As I embark on my journey with Angular 10, my goal is to display the current user in the profile.component.html and the navbar in app.component.html. Below you will find the relevant code snippets: users.ts export interface User { username : string ...

Generate the test output and save it to the distribution folder

When setting up my Angular 9 application in a Jenkins pipeline, I include two key steps: npm run test:prod, which translates to node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng test --prod; and npm run build:prod, translating to node --ma ...

Transcompiling TypeScript for Node.js

I'm in the process of developing a Node project using Typescript, and I've configured the target option to es6 in my tsconfig.json file. Although Node version 8 does support the async/await syntax, Typescript automatically converts it to a gener ...

Retrieving information from a JSON API using Angular with Typescript

Currently, I am dealing with an API JSON to fetch a list of countries, followed by a list of states, and then cities within that state and country. The challenge lies in the second API call that I make. In the beginning, I load a list of continents and the ...

Unable to initiate a new project in Node.js

As I was working on adding a new project in Angular, everything was running smoothly until today. However, when trying to create a new project today, I noticed that the node_modules folder is missing and encountered the following errors: https://i.stack.i ...

Generating PDF files from HTML documents using Angular

I am currently working on an Angular 11 application and I have a specific requirement to download a PDF file from a given HTML content. The challenge is that the HTML content exists independent of my Angular app and looks something like this: < ...

updating information automatically on page every X seconds for Angular component

I am trying to implement a way to automatically refresh the data of an Angular component every 30 seconds. Currently, I have used a simple setInterval function like this: this.interval = setInterval(() => { this.refresh(); // api call ...

analyzing properties through unit testing

Currently in the process of writing unit tests for computed properties. I have a file called fileOne.ts : export const fileOne = () => { const fx1 = computed ( () => { ... } ); const fx2 = computed ( () => { ... } ); const fx3 = comp ...

The number pipe is unable to interpret the given value, either because it is outside of the allowable range or cannot be

An error occurred while processing the specified value, it seems to be either unparsable or out of the acceptable range. Whenever I apply formatting with a pipe to a number in my object, I encounter this warning and the value fails to display. However, on ...

When the admin clicks the start button, redirect all users to the designated page

Currently, I am developing a voting application that features both an admin and users. My goal is for the voting campaign to kick off as soon as the admin clicks on the start button. Upon starting the voting process, I aim to redirect all users to a diff ...

Leverage the power of Template Input Variables beyond NgFor loop limitations

An example that is often encountered: <div *ngFor="let hero of heroes$ |async"> <span>{{hero.name}}</span> </div> I am wondering how to achieve the same functionality when heroes is not an Observable of an array of Heros, but in ...

Experiencing a problem in AngularJS 2 after including 'routing' in the imports section of app.module.ts

An issue arises when I include 'routing' in the imports section of app.module.ts app/app.routing.ts(18,23): error TS2304: Cannot find name 'ModuleWithProvider'. [0] app/app.routing.ts(18,65): error TS2304: Cannot find name 'AppRou ...

Converting an array into an object using Typescript and Angular

I have a service that connects to a backend API and receives data in the form of comma-separated lines of text. These lines represent attributes in a TypeScript class I've defined called TopTalker: export class TopTalker { constructor( pu ...

What could be the reason behind Cors preventing my API request?

Currently, I am in the process of developing a project that requires me to access an API that I have created. const endpoint = 'localhost:3000/api/v1/'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'appl ...

Importing Json in Angular 8: A detailed guide

I recently came across information that you can now directly import JSON in TypeScript 2.9 and made changes to my tsconfig.json file accordingly: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", " ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...