The Angular Ngx Charts display refuses to fill up despite attempts to populate

Currently, I am facing an issue with populating my charts using real data from an API. Here is the HTML code snippet in question:

<ngx-charts-bar-vertical
    [results]="popularCountriesData"
    [legend]="false"
    [showXAxisLabel]="false"
    [showYAxisLabel]="false"
    [xAxis]="true"
    [yAxis]="false"
    [gradient]="false">
</ngx-charts-bar-vertical>

In addition, this is a segment of the TypeScript file being utilized:

import {Component, OnInit} from '@angular/core';
import {ResearcherService} from "../../../services/researcher.service";
import {HttpErrorResponse} from "@angular/common/http";
import {PostCollection} from "../../../models/PostCollection";

@Component({
  selector: 'app-dashboard-custom',
  templateUrl: './dashboard-custom.component.html',
  styleUrls: ['./dashboard-custom.component.css']
})
export class DashboardCustomComponent implements OnInit {

    popularCountriesData: any = [];

    constructor(private researcherService: ResearcherService) { getData(); }

    private getData() {
        this.researcherService.restGetStatisticsCountry().subscribe((data: PostCollection[]) => {
                for (let i = 0; i < data.length; i++)
                    this.popularCountriesData.push({ name: data[i].name, value: data[i].posts.length });
                console.log(this.popularCountriesData)

            },
            (err: HttpErrorResponse) => {
                console.log(err.error);
            });
    }

    ngOnInit(): void {
    }

}

The challenge arises when running the code as the chart appears empty even though the console logs show the following data:

[
    {
        "name": "Japan",
        "value": 1
    },
    {
        "name": "Russia",
        "value": 1
    },
    {
        "name": "Netherlands",
        "value": 8
    }
]

To troubleshoot, I hardcoded the data directly into the TypeScript file as shown below:

popularCountriesData = [
        {
            "name": "Japan",
            "value": 1
        },
        {
            "name": "Russia",
            "value": 1
        },
        {
            "name": "Netherlands",
            "value": 8
        }
];

Surprisingly, this resulted in a proper chart display, which can be viewed at the following link: https://i.sstatic.net/Y3HXu.png

If you have any insights on what might be causing the initial issue, please share your thoughts.

Answer №1

Execute the this.getData(); method within the ngOnInit lifecycle hook.

Instead of using push, initialize a new array and assign it to popularCountriesData.

Here's an example:

    private getData() {
        this.researcherService.restGetStatisticsCountry().subscribe((data: PostCollection[]) => {
                const tempArray = [];
                for (let i = 0; i < data.length; i++)
                    tempArray.push({ name: data[i].name, value: data[i].posts.length });
                this.popularCountriesData = tempArray;
                console.log(this.popularCountriesData)

            },
            (err: HttpErrorResponse) => {
                console.log(err.error);
            });
    }

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 reason behind the issue of an infinite loop being resolved by including additional arrow function parentheses?

I'm currently using React for my project, and I've encountered an issue with the setState hook. Below is a snippet of my code: //state and handle function const [activeStep, setActiveStep] = React.useState(0); const handleStep = (index) => ...

Performing an asynchronous AJAX request to a PHP script to compute the total sum and retrieve

I have created an HTML table and utilized AJAX to send a POST request with two arrays. The first array is named rowValues and contains three arrays, one for each row. The second array is called columnValues and also has three arrays, one for each column. ...

Tips for utilizing interpolation for conditions instead of using *ngIf

For my application, I am using two different languages and have written them within two <option> tags. Is it possible to combine both conditions into a single <option> tag using interpolation? <option *ngIf="this.language=='en&apos ...

Using React - How to access prop values within child menus of Ant Design Dropdown

I have a feed of posts similar to a Facebook timeline, where each post has a dropdown menu with options for "edit, delete, report". Using the Ant Design UI library, I encountered an issue where I couldn't access the prop value "DeleteId" within the c ...

Setting up Mongoose with Admin JS in NestJS: A Step-By-Step Guide

After successfully configuring adminJS in my Nest JS application, it now runs smoothly on localhost:5000/admin. @Module({ imports: [ import('@adminjs/nestjs').then(({ AdminModule }) => AdminModule.createAdminAsync({ ...

Unable to trigger onActivated in Quasar (Vue 3) component

I can't seem to get the onActivated function in Vue 3 to trigger, even though I've implemented it before successfully. It's puzzling me as nothing seems to be happening. Currently, I'm using Vue version 3.0.0. Here is a snippet of my co ...

Creating multiple objects in a threejs instance with varying sizes and positions

Recently, I decided to try out the InstancedBufferGeometry method in order to improve performance when rendering thousands of objects. Specifically, I wanted to create instances of cube geometries with varying heights. AFRAME.registerComponent('insta ...

Ways to verify if a specific extjs panel has finished loading

After a specific panel has finished loading, I need to insert a JavaScript code (using the panel's ID). What is the best way to ensure that the panel has been fully rendered so that I can access its ID using document.getElementById? Thank you. ...

The $interval cancellation in AngularJS is not functioning as expected, and neither the onDestroy nor stateChangeSuccess events are working as

Below is a snippet of code I wrote to set up an interval that should be canceled when leaving the state, but it's not working as expected. var init = function () { $translatePartialLoader.addPart("app/bottling/palletTnT/palletTnT.grid"); ...

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

Integrating Node.js with static HTML documents

I'm currently exploring methods for making node.js API calls from static HTML. While I've considered using Express and similar template engines, I am hesitant since they would require me to adjust my existing HTML to fit their templates. Typicall ...

Using AJAX to query a database and updating a div tag with the submitted form entries

I need assistance in setting up a webpage with an AJAX form. The idea is that upon submission, the form's values will be used to search and query a database for results, which will then be displayed in the same DIV as the form. Any guidance or help o ...

I'm currently leveraging Vue.js and Python Flask for my backend development. I'm looking to establish some local variables. What is the best way to accomplish this?

Here is my Vue js file where I am utilizing two URLs from localhost. My goal is to create a configuration file that will allow me to make changes in one place and have those changes reflected throughout. <template> <div> <div class="glob ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

Send data from HTML forms to PHP without needing to reload the page

I’m currently developing a website that showcases data retrieved from a database using PHP. The site includes checkboxes within a form, and based on the user's selections, I want the data displayed in a certain div to refresh when they click ‘appl ...

Implementing the 'not-allowed' cursor style on disabled rows in Material UI datagrid

I have a specific disabled row in a Material UI data grid where users are unable to select or perform any actions on it. I am looking to display the cursor as "not-allowed" on this particular row. How can we apply styling to only this row since there is no ...

When you use npm uninstall, it deletes the package from package.json, but it does not remove it from the node_modules directory

After attempting to uninstall a package using npm uninstall (package_name) -s The package was successfully removed from package.json but remained in the node_modules folder. How can I effectively remove these unused packages from the node_modules folder? ...

Troubleshooting TextField malfunctioning after button click within Dialog on Material UI

My main objective is to focus on a Material UI TextField after closing a Dialog by clicking a button inside the Dialog. The code snippet below successfully accomplishes this task when triggered from a button that is not within a dialog component: focusOn ...

Is ajax testing with therubyracer (or execjs) worth trying out?

I'm looking to challenge myself by integrating and testing JavaScript code within a Ruby environment. My main goal is to utilize Ruby to set up the database, interact with it using my JavaScript model, and verify the JavaScript state without resorting ...

Incorporating the ThreeJS Transform tool into the Autodesk Forge Viewer

Trying to implement ThreeJS Transform control into the Forge Viewer by following an informative tutorial: The current issue is being able to add the Transform Control successfully, but not being able to interact with it. I had to make a slight adjustment ...