ng2-charts更新标签和数据

时间:2017-03-06 15:46:50

标签: javascript angular charts ng2-charts

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

我的模板:

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

    })
  }
}

14 个答案:

答案 0 :(得分:38)

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

在模板中:

<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语法:

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

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

答案 1 :(得分:11)

最近我不得不使用ng2-charts,我在更新数据方面遇到了很大的问题,直到我发现这个解决方案:

<div class="chart">
    <canvas baseChart [datasets]="datasets_lines" [labels]="labels_line" [colors]="chartColors" [options]="options" [chartType]="lineChartType">
    </canvas>
</div>

以及我在组件中的内容:

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

@Component({
    moduleId: module.id,
    selector: 'product-detail',
    templateUrl: 'product-detail.component.html'
})

export class ProductDetailComponent {
    @ViewChild(BaseChartDirective) chart: BaseChartDirective;

    private datasets_lines: { label: string, backgroundColor: string, borderColor: string, data: Array<any> }[] = [
        {
        label: "Quantities",
        data: Array<any>()
    }
];

private labels_line = Array<any>();

private options = {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
};


constructor() { }
ngOnInit() {

    this.getStats();

}
getStats() {

    this._statsService.getStatistics(this.startDate, this.endDate, 'comparaison')
        .subscribe(
        res => {
            console.log('getStats success');
            this.stats = res;

            this.labels_line = this.getDates();
            this.datasets_lines = [];

            let arr: any[];
            arr = [];
            for (let stat of this.stats) {
                arr.push(stat.quantity);
            }

            this.datasets_lines.push({
                label: 'title',
                data: arr
            });

            this.refresh_chart();

        },
        err => {
            console.log("getStats failed from component");
        },
        () => {
            console.log('getStats finished');
        });
}

refresh_chart() {
    setTimeout(() => {
        console.log(this.datasets_lines_copy);
        console.log(this.datasets_lines);
        if (this.chart && this.chart.chart && this.chart.chart.config) {
            this.chart.chart.config.data.labels = this.labels_line;
            this.chart.chart.config.data.datasets = this.datasets_lines;
            this.chart.chart.update();
        }
    });
}

getDates() {
    let dateArray: string[] = [];
    let currentDate: Date = new Date();
    currentDate.setTime(this.startDate.getTime());
    let pushed: string;
    for (let i = 1; i < this.daysNum; i++) {
        pushed = currentDate == null ? '' : this._datePipe.transform(currentDate, 'dd/MM/yyyy');
        dateArray.push(pushed);
        currentDate.setTime(currentDate.getTime() + 24 * 60 * 60 * 1000);
    }
    re

turn dateArray;
    }    
}

我确信这是正确的方法,希望这会有所帮助

答案 2 :(得分:8)

就像Deyd之前指出的那样,这是由Angular 2 +的变化检测和ng2-chart中的错误组合引起的。

根据我自己的观察(如果我错了,请纠正我),当调用changes: SimpleChanges时,Angular会在很短的时间内将几个更改合并到一个集合(ngOnChanges)中。 / p>

不幸的是,ng2-charts只检查是否已使用此集合更改数据集并更新它。否则它会完全重建整个图表。但是,由于更改检测的工作方式,可能会更改多个属性。然后,即使标签和可能的其他属性也已更新,只有数据集才会更新。请参阅ng2-charts中的ngOnChangesvalor-software/ng2-charts/src/charts/charts.ts

如果您不希望在应用中单独复制ng2图表并自行解决问题,则此问题的可能解决方法是使用JavaScript设置数据集的延迟时间短。内置函数setTimeout(callback: () => void, delay: number)

在:

@Component({
  selector: 'app-root',
  template: `
  <select (change)="onChange($event.target.value)">
    <option value="" disabled selected>Select your option</option>
    <option value="0">Option 0</option>
    <option value="1">Option 1</option>
  </select>

  <canvas baseChart
          chartType="bar"
          [datasets]="barChartData"
          [labels]="barChartLabels"
          [colors]="barChartColors">
  </canvas>
  `
})
export class AppComponent implements OnInit {
  chartData: string[];
  chartLabels: string[];
  chartColors: string[];

  onChange(id: string) {
    getFromApiById(id)
      .then(result => this._setChart(result.data, result.labels, result.colors));
  }

  private _setChart(data: string[], labels: string[], colors: string[]) {
    this.chartData = data;
    this.chartLabels = labels;
    this.chartColors = colors;
  }
}

后:

@Component({
  selector: 'app-root',
  template: `
  <select (change)="onChange($event.target.value)">
    <option value="" disabled selected>Select your option</option>
    <option value="0">Option 0</option>
    <option value="1">Option 1</option>
  </select>

  <canvas baseChart
          chartType="bar"
          [datasets]="barChartData"
          [labels]="barChartLabels"
          [colors]="barChartColors">
  </canvas>
  `
})
export class AppComponent implements OnInit {
  chartData: string[];
  chartLabels: string[];
  chartColors: string[];

  onChange(id: string) {
    getFromApiById(id)
      .then(result => this._setChart(result.data, result.labels, result.colors));
  }

  private _setChart(data: string[], labels: string[], colors: string[]) {
    this.chartLabels = labels;
    this.chartColors = colors;

    setTimeout(() => {
      this.chartData = data;
    }, 50);
  }
}

答案 3 :(得分:5)

使用BaseChartDirective我做了图表更新,它达到了目的。以下示例:

import { BaseChartDirective } from 'ng2-charts/ng2-charts';
在课堂内

添加如下

@ViewChild(BaseChartDirective) chart: BaseChartDirective;

当您要更改值时,请添加如下

setTimeout(() => {
if (this.chart && this.chart.chart && this.chart.chart.config) {
  this.chart.chart.config.data.labels = this.labels_pie;
  this.chart.chart.update();
}
});

答案 4 :(得分:3)

诀窍是清除标签和数据数组,下面的代码对我没用:( ```

clearCharts() {
    this.barChartLabels= [];
    this.barChartData= [
      {data: [], label: 'label1'},
      {data: [], label: 'label2'}
    ];
  }

However when I changed the way I cleared the data helped me (Using object reference)

clearCharts() {
    this.barChartLabels= [];
    this.emptyChartData(this.barChartData);
  }
   emptyChartData(obj) {
     obj[0].data = [];
     obj[1].data = [];
     obj[0].label = 'label1';
     obj[1].label = 'label2';
  }

```

答案 5 :(得分:2)

这是图书馆ng2-charts中的一个问题,为了解决这个问题,我已经在我的app目录中克隆了ng2-charts的github,并完成了以下步骤:

  • npm install
  • 在appmodule中从src目录导入ng-2charts.ts。
  • 将此updateChartLabels函数添加到chart.ts文件
  • onChanges函数中调用它。

public ngOnChanges(changes:SimpleChanges):void {     if(this.initFlag){

  if(changes.hasOwnProperty('labels')){
    console.log('labels changes ...');
    this.updateChartLabels(changes['labels'].currentValue);
  }
//..
//...
}

private updateChartLabels(newLabelsValues: string[] | any[]): void {
this.chart.data.labels = newLabelsValues;
}

答案 6 :(得分:2)

这是当前ng2-charts库的一个问题。

尝试修复此问题的新ng4图表库。

https://www.npmjs.com/package/ng4-charts

答案 7 :(得分:1)

还有另一种方法:

在你的HTML中

<canvas baseChart 
            [datasets]="ChartData"
            //...other stuff >
</canvas>

在组件中我有一个用新数据更新图表的函数,然后我克隆数据集并重新分配它

drawChart(){
    this.ChartData=[{data: this.dataX, label: 'X'}]; // this.dataX has new values from some place in my code
    //nothing happened with my chart yet, until I add this lines:        
    let clone = JSON.parse(JSON.stringify(this.ChartData));
    this.ChartData=clone;
   //other stuff like labels etc.
}

这适合我,希望它也适合你

答案 8 :(得分:1)

对于那些想要四处走走的人来说,现在您可以将标签和数据放在一个对象中,然后将该对象放在一个数组中,然后在html中遍历该数组。每次数组更改时,都会重新绘制元素。

每次更改时,在类型脚本中

data = [...]; labels = [...]; chartArray = [{data , labels }]

在您的html中

<canvas *ngFor="let chartData of chartArray " [datasets]="chartData.data" [labels]="chartData.labels" > </canvas>

答案 9 :(得分:0)

由于我没有设法使上述解决方案之一正常工作,所以我想贡献我的解决方案,以防万一有人偶然发现了这篇文章,并且对当前的方法感到困惑。

我有类似于@ mustafa918的HTML:

 <div>
  <canvas #canvas id="canvas" 
    baseChart [datasets]="lineChartData" 
    [labels]="lineChartLabels" 
    [colors]="lineChartColors"
    [options]="lineChartOptions" 
    [chartType]="lineChartType" 
    [legend]="lineChartLegend" 
    (chartHover)="chartHovered($event)"
    (chartClick)="chartClicked($event)">
  </canvas>
</div>

对于打字稿中的图表数据初始化,我有:

public lineChartData: Array<any> = [
    { data: this.heights, label: 'Heights History', type: 'line', fill: false},
    { data: this.widths, label: 'Widths History', type: 'line', fill: false }];

对我来说,它只能通过同时设置数据和标签来工作,并且不使用chart.update()-图表是对BaseChartDirective的引用。

我预先加载了相应的数据和标签,因此在 this.heights中,this.width this.lineChartLabels 是对应的数据。

例如:heights [i],widths [i]和lineChartLabels [i]上的条目与我的 elementArray 中的元素匹配,索引为i => element = {“ height”:30,“ width”: 20,“标签”:“框”}

setDatasets() {

//store data in chart references
var arrHeights = [];
for (var i in this.heights) {
  arrHeights.push({ x: this.lineChartLabels[i], y: this.heights[i] });
}

var arrWidths= [];
for (var i in this.widths) {
  arrWidths.push({ x: this.lineChartLabels[i], y: this.widths[i] });
}

this.lineChartData[0].data = arrHeights;
this.lineChartData[1].data = arrWidths;

}

我希望这对某人有所帮助:)祝你好运!

答案 10 :(得分:0)

我使用BaseChartDirective更新了图表,并达到了目的。下面的示例:

import { BaseChartDirective } from 'ng2-charts/ng2-charts';

在类中添加以下内容

@ViewChild(BaseChartDirective) chart: BaseChartDirective;

当您需要更改值时,请如下添加

 this.cart.ngOnChanges({});

答案 11 :(得分:0)

今天,我在类似问题上苦苦挣扎,看来ng2-charts库版本1.6.0的updateChartData函数内部存在一个巨大的错误。

这是原始功能:

        updateChartData = function (newDataValues) {
            if (Array.isArray(newDataValues[0].data)) {
                this.chart.data.datasets.forEach(function (dataset, i) {
                    dataset.data = newDataValues[i].data;
                    if (newDataValues[i].label) {
                        dataset.label = newDataValues[i].label;
                    }
                });
            }
            else {
                this.chart.data.datasets[0].data = newDataValues;
            }
        }

如您所见,这仅更新数据和标签,但所有其他属性都被保留。就我而言,我也想更新pointBorderColor,所以我决定覆盖它。

首先我获得对ng2-charts库的引用:

import { BaseChartDirective } from 'ng2-charts';

@ViewChild(BaseChartDirective) chart: any;

类型为“ any”非常重要,因为否则,打字稿将不允许我覆盖私有函数。

然后我修复函数中的错误并在afterVIew init中覆盖它:

ngAfterViewInit(){
    if (this.chart) {
        this.chart.updateChartData = function (newDataValues) {
            if (Array.isArray(newDataValues[0].data)) {
                this.chart.data.datasets.forEach(function (dataset, i) {
                    dataset.data = newDataValues[i].data;
                    if (newDataValues[i].pointBorderColor) {
                        dataset.pointBorderColor = newDataValues[i].pointBorderColor;
                    }
                    if (newDataValues[i].label) {
                        dataset.label = newDataValues[i].label;
                    }
                });
            }
            else {
                this.chart.data.datasets[0].data = newDataValues;
            }
        }.bind(this.chart);
    }
}

答案 12 :(得分:0)

我能够通过将处理程序转换为箭头函数来解决这个问题

export class HistogramChartComponent implements OnInit {

  constructor(private dataService: MyFruitService ) { }
  
  barChartOptions: ChartOptions = { responsive: true };
  barChartLabels: Label[] = ['Apple', 'Banana', 'Kiwifruit', 'Blueberry', 'Orange', 'Grapes'];
  barChartType: ChartType = 'bar';
  barChartLegend = true;
  barChartPlugins = [];

  barChartData: ChartDataSets[] = [
    { data: [45, 37, 60, 70, 46, 33], label: 'Best Fruits' }
  ];

  ngOnInit() {
    this.dataService
      .getDocument("Foobar")
      .subscribe(this.handleResponse);
  }

  handleResponse = (doc: MyFruitDocument) => {
      console.log('document: ', doc);
      
      let labels = doc.dataPoints.map(p => p.fruitName);
      let data = { data: doc.dataPoints.map(p => p.value), label: 'Best Fruits' };

      this.barChartLabels = labels;    
      this.barChartData = [ data ];
  }
}

答案 13 :(得分:0)

基于以上答案,我扩展了这个功能,现在一切正常!

TS 代码:

Declare : import { BaseChartDirective } from 'ng2-charts';

          @ViewChild(BaseChartDirective) chart: BaseChartDirective;

           public lineChartData: ChartDataSets[] = [
               { data: [0, 0, 0, 0, 0, 0, 0], label: 'Data 1' },
               { data: [0, 0, 0, 0, 0, 0, 0], label: 'Data 2' }
             ];

           public lineChartLabels: Label[] = ['Label1', 'Label2', 'Label3', 'Label4', 
                  'Label5', 'Label6';

TS Function:

    refresh_chart(){
        setTimeout(() => {
          if (this.chart && this.chart.chart && this.chart.chart.config) {
            this.chart.chart.config.data.datasets.forEach(x => {
              x.data = [];
            });
            let index = 0;
              this.chart.chart.config.data.datasets.forEach(x => {
                x.data = this.lineChartData[index].data;
                index++;
              });
              this.chart.chart.update();
          }
      }, 500);
      }

HTML 代码:

<canvas baseChart [datasets]="lineChartData" class="canvas-wh" [labels]="lineChartLabels"
                                [options]="lineChartOptions" [colors]="lineChartColors" [legend]="lineChartLegend"
                                [chartType]="lineChartType" [plugins]="lineChartPlugins">