Angular中使用Chart.js绘制饼图时项目运行报错求助
Angular中使用Chart.js绘制饼图时项目运行报错求助
Hey 各位,我现在在Angular项目里尝试用Chart.js配合ng2-charts绘制饼图,结果项目一运行就报错,折腾半天没找出问题,麻烦帮忙看看我的代码哪里出错了?
我的HTML代码:
<div> <canvas baseChart [data]="pieChartData" [colors]="colors" [labels]="pieChartLabels" [chartType]="pieChartType" > </canvas> </div>
Component.ts代码:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-pie-chart', templateUrl: './pie-chart.component.html', styleUrl: './pie-chart.component.css' }) export class PieChartComponent implements OnInit { pieChartData: number[] = [350,450,120]; pieChartLabels: string[] = ['xyz','Logistics','Main st Bakery','Acme hosting']; colors: any[] = [ { backgroundColor: ['#26547c','#ff6b6b','#ffd166'] } ]; pieChartType = 'pie' constructor(){} ngOnInit(){ } }
问题分析与解决办法
兄弟,我一眼就看到问题所在了——饼图的data数组和labels数组长度不匹配!
- 你的
pieChartData只有3个数值,但是pieChartLabels却有4个标签 - Chart.js绘制饼图时,要求每个数据项必须对应一个标签,数量不一致直接就会触发渲染错误
修正方案二选一:
- 补全数据项,让数据和标签数量一致:
// 新增一个数据值,同时给colors里加对应颜色 pieChartData: number[] = [350,450,120,200]; colors: any[] = [ { backgroundColor: ['#26547c','#ff6b6b','#ffd166','#06d6a0'] } ];
- 删除多余标签,保持和数据长度一致:
pieChartLabels: string[] = ['xyz','Logistics','Main st Bakery'];
另外还要确认你已经做好了基础依赖配置:
- 确保已经安装了
chart.js和ng2-charts:npm install chart.js ng2-charts - 在对应的模块(比如AppModule)里导入
ChartsModule:
import { ChartsModule } from 'ng2-charts'; @NgModule({ imports: [ // ...其他模块 ChartsModule ] }) export class AppModule { }
这样修改后,饼图应该就能正常渲染啦!
备注:内容来源于stack exchange,提问作者DavidShvili
相关产品推荐
相关产品推荐

