1

我目前有一个组件,我将在一个页面上显示多个图形,每个图形来自一个单独的 json 文件。我正在使用 ng2-charts 和 angular2,我不确定如何根据 json 数据加载我的图形,以及在一个组件中设置多个图形数据的最佳方法是什么。

这是我的 get 调用,它在我的组件文件中返回一个对象:

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);

    });
  }

这是我在组件文件中加载图表的代码:

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

示例 json 数据:

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

我的 html - 使用 ng2-charts:

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

目前 - 我能够在控制台中看到我有一个标签数组,但由于某种原因,即使我已将返回的标签推送到barChartLabelshtml 中使用的数组中,它们也没有显示在图表上。

4

1 回答 1

2

在将 RESTful 服务中的数据和标签检索到图表中时,我也遇到了同样的问题。我通过在图表上调用 ngOnChanges() 解决了这个问题。

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

更新:

使用上述方法时,在同一组件中加载第二个图表时出现问题。

ngOnChanges() 只会更新/加载第一个图表。

相反,我在每个画布中使用了 ngIf 指令,现在所有图表都加载了。

<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>
于 2017-04-28T01:37:30.173 回答