【问题标题】:Angular4 ng2-charts TypeError: Cannot read property 'length' of undefinedAngular4 ng2-charts TypeError:无法读取未定义的属性“长度”
【发布时间】:2021-10-01 21:00:23
【问题描述】:

我正在尝试使用从程序输出中收集的数据创建条形图。我正在使用一个变量来延迟画布加载,我最初认为这是一个时间问题,所以我使用了一个辅助函数来加载它,但不管我得到 core.js:4352 ERROR TypeError: Cannot read property 'length'在 ng2-charts.js:520 处未定义

app.component.ts

public barChartOptions: any = {
  scaleShowVerticalLines: false,
  responsive: true
};
public barChartType: string = 'bar';
public barChartLegend: boolean = false;
public barChartData: number[];
public barChartLabels: number[];

public tempData: number[] = [];
public tempLabels: number[] = [];
public chartReady: boolean = false;

grafico() {
  const url = this.root + 'grafico';
  this.httpclient.get(url).subscribe((res) => {
    for (let key in res) {
      if (res[key].uid == -1) {
        this.barChartLabels = this.tempLabels;
        this.barChartData = this.tempData;
        this.loadchart();
      } 
      else {
        this.tempData.push(res[key].data);
        this.tempLabels.push(res[key].uid);
      }
    };
  });
}

loadchart() {
  this.chartReady = true;
}

app.component.html

<canvas
    *ngIf="this.chartReady"
    baseChart
    style="height:230px" 
    [datasets]="this.barChartData" 
    [labels]="this.barChartLabels" 
    [options]="this.barChartOptions" 
    [legend]="this.barChartLegend" 
    [chartType]="this.barChartType" >
</canvas>

我问了一个更有经验的朋友,但他帮不了我,虽然这个问题在这里已经被问过很多次了,但我尝试了我在其他答案中可以找到的所有东西,但对我没有任何帮助,如果有人可以,我会很高兴帮帮我。

编辑: screenshot of error in browser

【问题讨论】:

  • 如果您可以在 ng2-charts.js 中附加屏幕截图错误,那就太好了:(第 520 行)
  • 完成!只能通过链接来做,因为我没有声誉
  • 尝试在不在循环之后调用“loadchart”方法。对于作为响应获得的数据,您应该在任何地方处理 null 条件。

标签: angular chart.js ng2-charts


【解决方案1】:

您似乎将数据数组传递给datasets 字段,这不起作用,您需要传递包含数据数组的数据集对象数组。

基本数据集对象:

{
    label: '# of Points',
    data: [7, 11, 5, 8, 3, 7],
}

【讨论】:

  • 谢谢!这个解决方案奏效了。必须更改数组类型,现在我的临时数组如下所示:this.tempData.push({data: res[key].data, label: ""}); this.tempLabels.push("ID " + res[key].uid.toString());
猜你喜欢
  • 2017-09-21
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 2020-07-20
相关资源
最近更新 更多