Potential issue with Jhipster: loading of data could be experiencing delays

I've encountered an issue with getting my chart to display properly. I am working on creating a chart using ng2-charts, where I retrieve data from a service and then display it on the chart. The problem arises when the data is not correctly displayed unless I insert an alert() function between fetching the data from the service and setting it on the chart.

lightData: LightData[];
public lineChartData = Array<any>();
public lineChartLabels = Array<any>();

ngOnInit() {
    this.lightData = []; // Array initialized as empty
    this.loadAll(); // Fetch all the data
    this.setChartData(); // Set the data on the chart
}

loadAll() {
    this.lightDataService.query().subscribe(
        (res: Response) => this.onSuccess(res.json(), res.headers),
        (res: Response) => this.onError(res.json())
    );
}

public setChartData(){
    for(let i = 0; i < this.lightData.length; i++)
    {
        this.lineChartLabels.push(this.lightData[i].id);
        this.lineChartData.push(this.lightData[i].value);
    }
}

private onSuccess(data, headers) {
    for (let i = 0; i < data.length; i++) {
        this.lightData.push(data[i]);
    }
}

private onError(error) {
    this.alertService.error(error.message, null, null);
}

The code doesn't work as expected - the chart remains empty. However, inserting an alert like this:

ngOnInit() {
    this.lightData = []; // Array initialized as empty
    this.loadAll(); // Fetch all the data
    alert("blabla"); // Alert to pause execution
    this.setChartData(); // Set the data on the chart
}

Makes it work! Strange how adding an alert resolves the issue. I've faced similar problems before with other functions and struggled to find a permanent fix.

Edit 1: I attempted to call the setChartData function within the asynchronous loadAll method:

lightData: LightData[];
public lineChartData = Array<any>();
public lineChartLabels = Array<any>();

ngOnInit() {
    this.lightData = []; // Array initialized as empty
    this.loadAll(); // Fetch all the data

}

loadAll() {
   this.lightDataService.query().subscribe(
   (res: Response) => {
      this.onSuccess(res.json(), res.headers);
      this.setChartData();
      },
   (res: Response) => this.onError(res.json())
   );
 }

public setChartData(){
  for(let i =0; i < this.lightData.length; i++)
  {
    this.lineChartLabels.push(this.lightData[i].id);
    this.lineChartData.push(this.lightData[i].value);
  }
}

private onSuccess(data, headers) {
    for (let i = 0; i < data.length; i++) {
        this.lightData.push(data[i]);
    }
}
private onError(error) {
    this.alertService.error(error.message, null, null);
}

Unfortunately, this approach still does not resolve the issue.

Answer №1

Your code does not pause and wait for the data to load, as it is done asynchronously. The current order of execution in your code is:

 this.loadAll(); // initiates the request
 this.setChartData(); // sets an empty list as data initially
 this.onSuccess(res.json(), res.headers); // completion of the request happens later

To ensure that the chart data is set after receiving the data, you should call setChartData within the success handler of the request.

loadAll() {
  this.lightDataService.query().subscribe(
    (res: Response) => {
      this.onSuccess(res.json(), res.headers);
      this.setChartData();
    },
    (res: Response) => this.onError(res.json())
  );
}

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

How can I code a div to automatically scroll to the top of the page?

I'm attempting to implement something similar in WordPress - I want a div containing an advertisement to initially start 300px down the page, then scroll up with the page until it reaches the top, and finally stay there if the user continues to scroll ...

Error message: 'firebase/app' does not export 'app' (imported as 'firebase') - Import attempt failed

Encountered a strange issue today. As I tried to import firebase, an error popped up: ./node_modules/firebaseui/dist/esm.js Attempted import error: 'app' is not exported from 'firebase/app' (imported as 'firebase'). The setup ...

Tips on implementing a script injected through the JS console to update form data in an Angular webpage and ensure that the changes are successfully saved

I am currently working on enhancing an existing electron app integrated with Angular. The main goal is to inject a script once the application is loaded in order to add a hotkey for efficiency. This hotkey should automatically click an edit button, input s ...

Is there a way for me to receive numerical values instead of NaN?

I'm currently facing a challenge in creating a Fibonacci number generator and I've hit a roadblock. It seems like I have a solution, but the appearance of NaN's is causing me some trouble. function fibonacciGenerator (n) { var output = [ ...

Exploring the possibilities of utilizing package.json exports within a TypeScript project

I have a local Typescript package that I am importing into a project using npm I ./path/to/midule. The JSON structure of the package.json for this package is as follows: { "name": "my_package", "version": "1.0.0&q ...

What is the best way to make an image expand when clicked, align it in the center of the webpage, and have it return to its original position with just one more click by utilizing

Currently, this is the code I am working with. The JavaScript functionality is working well, however, there seems to be an issue where the image does not return to its original size on a second click. Additionally, I am having trouble getting the CSS to ce ...

Saving a promise object as a $scope variable in AngularJS: A quick guide

When working with my application, I use Constants.getContants as a promise to retrieve all the necessary constants. I want to store this information in a $scope variable so that it can be easily accessed throughout the controller or application. However, I ...

Quirks and nuances when using p5's pixel fill function

I am currently utilizing the p5.js library to work on a program that is designed to automatically fill closed spaces. However, I am encountering an issue where the program sometimes fills half-closed loops for reasons unknown to me. If anyone could provide ...

What is the best way to display and conceal various elements with each individual click?

Utilizing the onClick function for each triggering element, I have implemented a show/hide feature for multiple element IDs upon click. The default setting is to hide the show/hide elements using CSS display property, except for the initial 3 main elements ...

How can I display a popup window within an iframe on a separate full page?

I am facing an issue while creating an HTML table using AngularJS with a popup. The problem is that I want the popup window, which shows a graph, to open up on the entire page instead of in a specific div. My desired output should look like this: Currentl ...

How can I prevent list items in jQuery Mobile from being truncated with ellipses?

Here is the list I am working with: <ul id="linksList" data-role="listview" data-inset="true" data-filter="true"> <!-- Dynamic contents! --> </ul> This list pulls its data from a local XML file (RSS feed). I am looking f ...

Tips for causing the JavaScript confirm alert to appear just a single time

My latest project involves creating a confirm alert that notifies users when their password is about to expire, prompting them to change it. The functionality for this alert is located in the header section of the website. Upon successful login, users are ...

Finding a solution for duplicate date selections in NextJS using react-calendar

I am currently working on a calendar component using NextJS, typescript, tailwindcss, and the react-calendar library. I have encountered an issue with duplicate dates appearing in the calendar when selecting a date range. Although I have managed to handle ...

Using Typescript with Vue.js: Defining string array type for @Prop

How can I properly set the type attribute of the @Prop decorator to be Array<string>? Is it feasible? I can only seem to set it as Array without including string as shown below: <script lang="ts"> import { Component, Prop, Vue } from ...

Adjust rankings based on the number of upvotes received by a project

I'm facing a challenge with ranking projects based on the number of votes they receive. No matter the vote count, the project always ends up getting ranked as 1. To address this issue, I developed a function to manage the rank count and a return hand ...

Exporting stylesheets in React allows developers to separate

I am trying to figure out how to create an external stylesheet using MaterialUI's 'makeStyles' and 'createStyles', similar to what can be done in React Native. I'm not sure where to start with this. export const useStyles = m ...

Record modified fields using Angular Reactive Forms and store them in a list

Is there a method available that can identify and return the fields that have been modified within a form? I am looking to generate a list of string values for the changed fields. I am dealing with a complex form containing approximately 30 different fiel ...

Reactjs implemented with Material UI and redux form framework, featuring a password toggle functionality without relying on hooks

Currently, I am working on a react project where I have developed a form framework that wraps Material-UI around Redux Form. If you want to check out the sandbox for this project, you can find it here: https://codesandbox.io/s/romantic-pasteur-nmw92 For ...

Using TypeScript to eliminate duplicate values when constructing an array with various properties

Recently, I received an array from an API that has the following structure: results = [ {name: 'Ana', country: 'US', language: 'EN'}, {name: 'Paul', country: 'UK', language: 'EN'}, {name: & ...

Having trouble retrieving accurate JSON data from an excel workbook

Currently, I am utilizing the npm module xlsx for the purpose of writing and reading JSON data. My goal is to take this JSON data and write it into an Excel file: { "name": "John", "class": 1, "address" : [ { "street": "12th Cross", "city": "London" }, { ...