Tips for accessing property values with TypeScript in Angular 7

I am facing an issue with retrieving the value of countOnProgress from my property. The problem is that I can successfully get the value of countOnProgress when I subscribe to it, but outside of the subscription, countOnProgress returns 0. This means that I can't use countOnProgress in progressLastYear function. How can I set the value of countOnProgress to retain the subscribed value without it returning to 0?

import { Component, OnInit, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { DashboardService } from './dashboard.service';
import { Observable, of, timer } from 'rxjs';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/observable/timer';

@Component({
  templateUrl: 'dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  alive = true;
  countOnProgress:number = 0;
  max: number = 200;
  value: number = 100;
  stacked: any[] = [];

  constructor(@Inject (DashboardService) private dashboardService: DashboardService){ 
  }

  ngOnInit(): void {
    Observable.timer(0, 30000)
    .takeWhile(() => this.alive)
    .subscribe(() => {
      this.dashboardService.getCountProgress().subscribe(resp => {
        this.countOnProgress = resp.d;
        console.log(this.countOnProgress); //It found the data
      })
    });
    this.progressLastYear();
  }

  progressLastYear(): void{
    const types = ['success', 'info', 'warning', 'danger'];
    const values = [this.countOnProgress];
    console.log(values);
    this.stacked = [];
    for (let i = 0; i < 5; i++) {
      this.stacked.push({
        value: values[1],
        type: types[i],
        label: values[1]
      });
      console.log(this.stacked); //The datas: 0, succes, 0 (didnt get countOnProgress' value)
    }
  }
}

Thank you

Answer №1

Revise your code as shown below:

ngOnInit(): void {
    Observable.timer(0, 30000)
    .takeWhile(() => this.alive)
    .subscribe(() => {
      this.dashboardService.getCountProgress().subscribe(resp => {
        this.countOnProgress = resp.d;
        console.log(this.countOnProgress); //Data successfully retrieved
        this.progressLastYear();   // < -- function call placed here now
       })
    });

  }

Why doesn't my code work properly?

JavaScript is asynchronous and does not wait for I/O requests to complete before moving on to the next line of code.

In your code, both Observable.timer(0, 30000) and

this.dashboardService.getCountProgress()
are asynchronous operations. Therefore, JavaScript does not wait for them to finish before proceeding to the next line of code. This resulted in the this.progressLastYear() method being called before the service call was completed, leading to an issue with retrieving the value of countOnProgress.

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

Using Typescript to extract/calculate types with limitations without the need to explicitly extend or broaden them

I have a function called build that constructs a User object using the provided parameters. I want to define the function in such a way that it recognizes which parameters are being passed and incorporates them into the return value. Initially, I thought ...

Using React, PIXI, and Zustand can sometimes lead to stale state issues when handling mouse events

I currently have a Pixi canvas that utilizes pointer handlers. Users are able to click on a point within a 'sequence' and move it. Recently, I came across an issue with the mouse handlers having stale state. To resolve this, I began recreating t ...

Changes made to the updated component fields are not reflecting on the user interface

I've encountered an issue where I can't seem to update a variable in a component that is being displayed on the UI. Even though the content of the variable changes correctly, the UI fails to reflect this change. Strangely enough, when checking th ...

Troubleshooting compilation issues when using RxJS with TypeScript

Having trouble resolving tsc errors in the code snippet below. This code is using rxjs 5.0.3 with tsc 2.1.5 import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import 'rxjs/Rx'; let subject ...

During rendering, the instance attempts to reference the "handleSelect" property or method which is not defined

I've incorporated the Element-UI NavMenu component into my web application to create a navigation bar using Vue.JS with TypeScript. In order to achieve this, I have created a Vue component within a directory called "navBar," which contains the follow ...

Is there a way for me to retrieve the value that has been set within the cy.get() function in Cypress using Typescript?

Is there a way to retrieve the value of the getLength function without it returning undefined? How can I access the value in this case? Here is my code snippet: const verifyValue = () => { const selector = 'nz-option-container nz-option-item&apo ...

Error in backend request originating from an Angular 2 source

I have an email for user verification that includes a link to my angular 2 route localhost:4200/verify/{userId}. When the user clicks on this link, it directs them to the angular 2 route where I extract the userId from the URL and pass it into my service. ...

Angular lifecycle event

When using the Firebase JS SDK in an Angular project and implementing lifecycle hooks, such as afterViewInit, I noticed that the console message repeats infinitely. How can I ensure that the message only appears once in the console? Thank you for any help ...

Angular 5 is not compatible with jQuery

I'm attempting to integrate jQuery into my Angular 5 project, focusing on utilizing this specific library: https://codepen.io/rstrahl/pen/eJZQej Below are the steps I've followed: -->Created a new app ng new myApp -->Navigated to the n ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

Difficulty arises when attempting to load Silverlight within an Angular2 component

Issue with Silverlight Component Loading When embedding and loading the Silverlight.xap file directly inside an HTML page, everything works perfectly. However, when we move the same code inside a component, the Silverlight content fails to load. Interest ...

Tips on utilizing Selenium with Java to locate and interact with elements on an Angular web application

I'm facing challenges with automating an Angular web app. Despite trying simple code, it still isn't working. Here's an example of my code: @BeforeClass public void setUp() { ChromeOptions options = new ChromeOptions(); ...

Lately, I've run into some challenges while trying to set up a category filter for an online store being developed with NodeJs and Angular

When examining the code snippets below, it appears that the filter functions are not functioning as expected. Component HTML: <div class="products-page"> <div class="grid"> <div class="col-3"> <h4 ...

Ways to display dynamic information in a vertical list using HTML (MEAN stack)

I am receiving an array of data from the backend and looking for a way to display them in a vertical list using HTML. Can anyone help me with this? Below is my current code snippet. TS: this.sub = this.route.params.subscribe(params => { this.http.g ...

Using Angular 8 for Filtering Firebase Data

I need to implement a filter on the titles of my stored data, but I am facing an issue where the structure of the filtered data changes. The original "key" of the data gets deleted by the filter and is replaced with an index instead. Link to repository : ...

Tips for utilizing the keyword 'this' within a Promise

Seeking assistance with resolving an issue involving an undefined error when attempting to make an http request within a Promise function. The error occurs due to this.http.post being undefined, indicating that there is an issue with accessing this properl ...

Ways to reuse test cases across different test suites in Protractor

There are some shared test cases that can be utilized across different test suites. For example, suppose suite x and suite y both require the same set of test cases to function properly. To address this, a separate .js file containing the shared code has ...

Escape from the abyss of callback hell by leveraging the power of Angular, HttpClient, and

I'm currently grappling with understanding Angular (2+), the HttpClient, and Observables. I'm familiar with promises and async/await, and I'm trying to achieve a similar functionality in Angular. //(...) Here's some example code showca ...

Steps for implementing a conditional rendering in your codeHere is a

I've encountered an issue while attempting to implement conditional rendering. The error I'm getting is Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'types&apos ...

What steps can be taken to skip the email verification in Auth0 when updating a password by confirming the old password?

I am in need of creating a personalized page for changing passwords using auth0. I want the process to involve directly modifying the password without requiring an email with a password change link. Additionally, it needs to have a feature for confirming t ...