ng2-charts更新标签和数据 [英] ng2-charts update labels and data

查看:182
本文介绍了ng2-charts更新标签和数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ng2-chart动态创建图表,
我从角度2服务获取信息,当我只更改图表的标签时它工作,当我更改数据时它只能工作,但是当我改变了两个只是数据在图表中更新。对这种奇怪的行为有任何解释。

I'm trying to create dynamically a chart using ng2-chart, I get information from an angular 2 service, when I change only labels of chart it works and when I change data only it works, but When I change both just data are updated in the chart. have any one an explication for this strange behavior.

我的模板:

<canvas baseChart height="130" width="180"

                                              [data]="doughnutChartData"
                                              [labels]="doughnutChartLabels"
                                              [chartType]="doughnutChartType"
                                              (chartHover)="chartHovered($event)"
                                              (chartClick)="chartClicked($event)"></canvas>

我的班级:

export class PlDoughnutComponent implements OnInit {

  constructor(private homeService: TileServiceService) { }

  ngOnInit() {
    this.updatePLdoughnut();

  }

  public util : UtilService = new UtilService();
  public doughnutChartLabels:string[] = ['Download Sales'];
  public doughnutChartData:number[] = [0,0,100];
  public doughnutChartType:string = 'doughnut';

  public updatePLdoughnut(){

    this.homeService.getTile().
    then(res => {

      this.doughnutChartLabels =  res.PLtypes;
      this.doughnutChartData = this.util.objectToIntArray(res.PLByTypes);

    })
  }
}


推荐答案

显然,如果你不修改标签数组的原始参考,它似乎起作用,至少对我而言。我的意思是,如果你想要一套完全不同的标签,你应该这样做:

Apparently, if you do not modify the original reference to the labels array, it seems to work, at least for me. I mean, if you want a completely different set of labels, you should do something like this:

在模板中:

<canvas baseChart
  [datasets]="lineChartData"
  [labels]="lineChartLabels"
  [options]="lineChartOptions"
  [chartType]="'line'"></canvas>

在ts组件中:

this.lineChartLabels.length = 0;
for (let i = tempLabels.length - 1; i >= 0; i--) {
  this.lineChartLabels.push(tempLabels[i]);
}

或者,使用新的ECMAScript语法:

Or, using new ECMAScript syntax:

this.lineChartLabels.length = 0;
this.lineChartLabels.push(...tempLabels);

关键可能是 this.lineChartLabels.length = 0; 语句,它通过将其长度设置为0来实际清空数组,而不修改引用。
希望这会有所帮助!

The key is maybe the this.lineChartLabels.length = 0; statement, which practically 'empties' your array by setting its length to 0, without modifying the reference. Hope this helps!

这篇关于ng2-charts更新标签和数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆