ng2-charts不会显示更新的标签,只显示数据

时间:2017-04-08 13:47:18

标签: angular typescript ng2-charts

我有一个使用ng2-charts包的angular(2)应用程序。我的一个组件显示一个饼图,其中包含从服务器查询的数据。该组件如下所示:

export class PieChartComponent implements OnInit {
  data: Array<number> = [];
  labels: Array<string> = ['', '', '', ''];
  private line: string;
  private department: string;

  constructor(public dataService: LineService, private route: ActivatedRoute) {
    this.route.params.forEach((params: Params) => {
      this.department = params['dep'];
      this.line = params['id'];
    });
  }

  ngOnInit() {
    this.dataService.getLineTAL(this.department, this.line).forEach(result => {
      this.data = result.map(val => val.val);
      this.labels = result.map(val => val.tag);
    });
  }    
}

和html:

<div style="display: block">
  <canvas baseChart [data]="data" [labels]="labels" [chartType]="'pie'" (chartClick)="chartClicked($event)" width="1" height="1"></canvas>
</div>

运行调试器时,我可以验证this.labels是否已更新为正确包含字符串数组,这些字符串应该是图表数据标签的值。但是,图表会使用正确的数据进行渲染,但没有值,因此在悬停时我得到:

enter image description here

我也不确定为什么默认颜色都变为灰色?我有这个逻辑和UI工作正常,直到我把它旋转到它自己的组件。

正如其他一些问题所述,我还尝试在服务调用之前添加this.chart.ngOnChanges({});,其中图表为@ViewChild(BaseChartDirective) chart: BaseChartDirective;。我还在结果映射结束时尝试this.labels = this.labels.slice();尝试强制刷新,但都没有帮助。

更新

如评论中所述,在ngAfterViewInit事件中,图表对象包含正确的数据和标签属性(数组)。然而仍然没有正确显示。

2 个答案:

答案 0 :(得分:5)

当您尝试同时更新两个属性(标签和数据)时,ng2-chart的问题就变成了,简单的解决方案是直接设置数据并在0超时内标记:

ngOnInit() {
    this.dataService.getLineTAL(this.department, this.line).forEach(result => {
      this.data = result.map(val => val.val);
      setTimeout( () => {this.labels = result.map(val => val.tag)};
    });
  } 

有了这个,你必须完成。

答案 1 :(得分:0)

我面临着类似的问题。我通过使用 loaded 标志解决了它。

像这样放置您的HTML代码->

<canvas *ngIf="loaded" baseChart [data]="data" [labels]="labels" [chartType]="'pie'" (chartClick)="chartClicked($event)" width="1" height="1"></canvas>

您的component.ts文件为->

export class PieChartComponent implements OnInit {
  data: Array < number > = [];
  labels: Array < string > = ['', '', '', ''];
  private line: string;
  private department: string;
  loaded = false;

  constructor(public dataService: LineService, private route: ActivatedRoute) {
    this.route.params.forEach((params: Params) => {
      this.department = params['dep'];
      this.line = params['id'];
    });
  }

  ngOnInit() {
    this.dataService.getLineTAL(this.department, this.line).forEach(result => {
      this.data = result.map(val => val.val);
      this.labels = result.map(val => val.tag);
    });
  }
  this.loaded = true;
}

相关问题