Angular 15中ng2-charts配置双Y轴报错,如何排查与解决?
Angular 15中ng2-charts双Y轴折线图报错修复
问题代码
用户实现双Y轴折线图的代码如下:
public chart1Data: ChartConfiguration<'line'>['data'] = { labels: this.labelData, datasets: [ { data: this.loadData, label: 'Engine Load', fill: false, tension: 0.5, borderColor: 'rgba(255,0,0,1)', backgroundColor: 'rgba(255,0,0,0.5)', yAxisID: 'y-axis-l', }, { data: this.rpmData, label: 'Engine speed (RPM)', fill: false, tension: 0.5, borderColor: 'rgba(255,128,0,1)', backgroundColor: 'rgba(255,128,0,0.3)', yAxisID: 'y-axis-r', }, ], }; public lineChartOptions: ChartOptions<'line'> = { responsive: true, scales: { yAxes: [ { id: 'y-axis-l', position: 'left', }, { id: 'y-axis-r', position: 'right', } ] } }; public lineChartLegend = true;
报错信息
启动应用后出现TypeScript类型错误:
error TS2322: Type '{ id: string; position: string; }[]' is not assignable to type '_DeepPartialObject<{ type: "time"; } & Omit<CartesianScaleOptions, "max" | "min"> & { min: string | number; max: string | number; suggestedMin: string | number; ... 5 more ...; ticks: { ...; }; }> | ... 4 more ... | undefined'. Type '{ id: string; position: string; }[]' is not assignable to type '_DeepPartialObject<{ type: "timeseries"; } & Omit<CartesianScaleOptions, "max" | "min"> & { min: string | number; max: string | number; suggestedMin: string | number; ... 5 more ...; ticks: { ...; }; }>'. Types of property 'reverse' are incompatible. Type '() => { id: string; position: string; }[]' is not assignable to type 'boolean | undefined'. 152 yAxes: [ ~~~~~
报错原因
Angular 15配套的ng2-charts依赖Chart.js v3+版本,该版本彻底废弃了v2时代的yAxes数组配置写法。原代码使用的是Chart.js v2的双Y轴语法,与v3+的类型定义完全不兼容,导致TypeScript类型校验失败。
修复方案
将lineChartOptions中的双Y轴配置改为Chart.js v3+的标准写法:直接在scales对象中以轴ID为键,定义每个Y轴的配置。修改后的完整代码如下:
public chart1Data: ChartConfiguration<'line'>['data'] = { labels: this.labelData, datasets: [ { data: this.loadData, label: 'Engine Load', fill: false, tension: 0.5, borderColor: 'rgba(255,0,0,1)', backgroundColor: 'rgba(255,0,0,0.5)', yAxisID: 'y-axis-l', }, { data: this.rpmData, label: 'Engine speed (RPM)', fill: false, tension: 0.5, borderColor: 'rgba(255,128,0,1)', backgroundColor: 'rgba(255,128,0,0.3)', yAxisID: 'y-axis-r', }, ], }; public lineChartOptions: ChartOptions<'line'> = { responsive: true, scales: { // 左侧Y轴配置 'y-axis-l': { position: 'left', // 可添加额外配置,比如刻度样式、颜色等 }, // 右侧Y轴配置 'y-axis-r': { position: 'right', // 可按需添加额外配置,比如隐藏网格线 // grid: { // drawOnChartArea: false // } } } }; public lineChartLegend = true;
修改后,TypeScript类型校验会通过,双Y轴折线图可正常渲染。
内容的提问来源于stack exchange,提问作者Nooh Ahamad
相关产品推荐
相关产品推荐

