错误TS2322:类型“string”不能分配给类型“keyof ChartTypeRegistry”

tag5nh1u  于 2023-04-11  发布在  Chart.js
关注(0)|答案(2)|浏览(272)

home.component.ts

global: boolean = false;
country!: string;
data: GlobalData;
dailyData: any[] = [];
countries: any[] = [];
lineChartData: any[] = [
  {
    data: [65, 64, 33, 44],
    label: 'Temp label'
  }
];
lineChartType = "line";
lineChartLabels: any[] = [
  'label01', 'label02', 'label03'
];
barChartData: any[] = [
  {
      data: [65, 76, 33],
      label: 'Label'
  }
];

home.component.html

<canvas baseChart
    [chartType] = "lineChartType"
    [datasets] = "lineChartData"
    [labels] = "lineChartLabels"
>
</canvas>

错误:
类型“string”不能分配给类型“keyof ChartTypeRegistry”
错误行:

[chartType] = "lineChartType"

页面出错页面出错
我需要一个解决方案。尝试在谷歌上找到解决方案,但我找不到它。

lmvvr0a8

lmvvr0a81#

仅供参考,ChartTypeRegistry是由chart.js在version 3.0 and later中引入的。
因此,我得出结论,您安装的chart.js与最新的ng 2-chart(版本2.4.2)不兼容。
为了重现相同的问题,我安装了
chart.js 3.4**作为以下链接:
Sample project (chart.js v 3.4)

解决方案(chart.js 3.0之前版本)

根据ng2-charts - npm
你需要安装chart.js:

npm install chart.js@2.9.4

npm install @types/chart.js@2.9.33

Sample solution (chart.js v 2.9.4)

解决方案(chart.js 3.0及以上版本)

使用ChartType类型指定lineChartType

import { ChartType } from 'chart.js';

public lineChartType: ChartType = "line";

Sample solution (chart.js v 3.0)

evrscar2

evrscar22#

有一个例子Chart.js从4.0.1 +版本,像我解决

import { Chart, ChartType } from 'chart.js/auto';

    chartTypes: {[key: string]: ChartType} = {
       line: 'line',
       bar: 'bar'
    };

    //...code
    lineChartType = this.lineChartType['line'];

相关问题