Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

540
Visualizações
loading graph data from json object in angular2 using ng2-charts

I currently have a component in which i will be displaying multiple graphs on one page and each from a separate json file. I am using ng2-charts and angular2 and i am not sure how to have my graph load up based on json data and what is the best way of setting up multiple graph data in one component.

Here is my get call that returns an object in my component file:

dataType: any=[];
 getData(){
    this.dataService.getDataType().subscribe((response) => {this.dataType = response; 
    for(let item of this.dataType){
      this.barChartLabels.push(this.dataType.name);
    }
    console.log(this.itemNames);

    });
  }

This is my code for loading my graph in component file:

public barChartOptions: any = {
  scaleShowVerticalLines: false,
  responsive: true
};
public barChartLabels: any =[]; //LOAD from dataType.label
public barChartType: string = 'horizontalBar';
public barChartLegend: boolean = true;

public barChartData: any[] = //LOAD from dataType.data

Sample json data:

[
  {
    "id": 1,
    "name": "Test 1",
    "display": "Test 1",
    "score": 45
  }, ...
]

My html - using ng2-charts:

<canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]="barChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)">
                    </canvas>

Currently- i was able to see in the console that i have an array of labels but for some reason they are not being displayed on the graph even though i have pushed my returned labels into the barChartLabels array which is used in the html.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I also had the same problem when retrieving data and labels from my RESTful service into my charts. I resolved this problem by calling ngOnChanges() on the chart.

import { Component, AfterViewInit, OnInit, ViewChild, SimpleChanges } from '@angular/core';
import { BaseChartDirective } from 'ng2-charts';

export class DashboardComponent implements OnInit, AfterViewInit {
    @ViewChild(BaseChartDirective)
    public chart: BaseChartDirective;

    ngAfterViewInit() {
        this.updateCharts();
    }

    public updateCharts(): void {
        console.log('updateCharts()');

        setTimeout(() => {
            this.chart.ngOnChanges({} as SimpleChanges);
        }, 100);
    }
}

Update:

There was problems with loading a second chart witin the same component when using the above approach.

The ngOnChanges() will only update/load the first chart.

Instead I used the ngIf directive within each canvas and all charts load now.

<canvas baseChart *ngIf="pastChartLabels.length > 0" [colors]="pastChartColors" [datasets]="pastChartData" [labels]="pastChartLabels" [options]="pastChartOptions"
    [chartType]="pastChartType" [legend]="pastChartLegend" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)"></canvas>

<canvas baseChart *ngIf="recentChartLabels.length > 0" [colors]="recentChartColors" [datasets]="recentChartData" [labels]="recentChartLabels" [options]="recentChartOptions"
    [chartType]="recentChartType" [legend]="recentChartLegend" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)"></canvas>
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda