ng2-charts bar graph not displaying data/graph labels

*爱你&永不变心* 提交于 2019-12-05 19:22:41

UPDATE 2

As the problem is still there when initializing the chart data async in subscribe, a working solution is to use a loading flag combined with *ngIf to wait for the data from the service to be loaded before initializing the chart.

That would look like this:

Template:

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

Component:

loaded = false;

getData(){
    this.dataService.getData().subscribe(data => {
      this.resultData = data;
      this.barChartLabels = this.resultData.map(item => item.label);
      this.barChartData = this.resultData.map(item => item.data);
      this.loaded = true;
    }
}

Here is a PLUNKER

UPDATE 1

According to your comment, this helped with displaying the data, but the labels are still not showing up. From the code you have provided, it's really hard to know why, but it's probably something wrong with your data. Can you log the barChartData and barCharLabels so I can have a look at it?

Here is a working plunker for your example, but with hard-coded data: PLUNKER

ORIGINAL

The ng2-chart is using ngOnChanges internally to catch changes of its input data. This means that modifying the arrays you have inputed to it will not trigger a change. And since your barChartLabels and barChartData array are already initialize as empty arrays, that is what the chart will use.

What you will need to do to trigger ngOnChanges is change the actual instances of barChartLabels and barChartData when you receive new data.

Replace this inside your getData method:

this.result.forEach( item => {
   this.barChartLabels.push(item.label);
   this.barChartData.push(item.dataInfo);
})

With something like this:

this.barChartLabels = this.result.map(item => item.label);
this.barChartDatat = this.result.map(item => item.dataInfo);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!