Home > Mobile >  Angular Ngx Charts chart stays empty
Angular Ngx Charts chart stays empty

Time:12-06

I have a problem. I am trying to fill my charts with real data from my API. To do that I have the following html:

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

And my typescript file is:

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) { this.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 {
    }

}

When I run this code, my chart is empty, while I can see in the console log:

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

If I copy this data and hardcode it in the typescript file like this:

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

The chart has a result: enter image description here

What am I doing wrong?

CodePudding user response:

Call this.getData(); from ngOnInit.

Instead of push create new array and assign that new array to popularCountriesData

Something like:

    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);
            });
    }
  • Related