Actualmente tengo un componente en el que mostraré múltiples gráficos en una página y cada uno de un archivo json separado. Estoy usando ng2-charts y angular2 y no estoy seguro de cómo hacer que mi gráfico se cargue en función de los datos json y cuál es la mejor manera de configurar múltiples datos de gráficos en un componente.
Aquí está mi llamada de obtención que devuelve un objeto en mi archivo de componentes:
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); }); }Este es mi código para cargar mi gráfico en el archivo de componentes:
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.dataEjemplo de datos json:
[ { "id": 1, "name": "Test 1", "display": "Test 1", "score": 45 }, ... ]Mi html - usando ng2-charts:
<canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]="barChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)"> </canvas> Actualmente, pude ver en la consola que tengo una matriz de etiquetas, pero por alguna razón no se muestran en el gráfico a pesar de que presioné mis etiquetas devueltas en la matriz barChartLabels que se usa en el html.
También tuve el mismo problema al recuperar datos y etiquetas de mi servicio RESTful en mis gráficos. Resolví este problema llamando a ngOnChanges() en el gráfico.
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); } }Actualizar:
Hubo problemas al cargar un segundo gráfico dentro del mismo componente al usar el enfoque anterior.
ngOnChanges() solo actualizará/cargará el primer gráfico.
En su lugar, utilicé la directiva ngIf dentro de cada lienzo y todos los gráficos se cargan ahora.
<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>