Chart.js core.js:6162 错误错误:“line”不是注册的控制器

Tat*_*ova 7 chart.js angular

 const gainContext = this.gainRef.nativeElement.getContext('2d')
  gainContext.canvas.height = '300px'

  new Chart(gainContext, createChartConfig(gainConfig))


function createChartConfig({type, labels, data, label, color}: ChartConfig): ChartConfiguration<"line">{

  console.log('3 Chart.defaults', Chart.defaults)

  return {
type: "line",
data: {
  labels,
  datasets: [
    {
      label,
      data,
      borderColor: color,
      stepped: false,
      fill: false
    }
  ]
}
  }
Run Code Online (Sandbox Code Playgroud)

这不起作用:它无法识别官方文档中必须的类型属性。

让 myChart = new Chart(gainContext, { type: 'line',

我做错了什么?

小智 18

我们可以通过三种方式做到这一点

  1. 通过进口

    import { Chart, registerables } from 'chart.js';

然后注册所有组件

Chart.register(...registerables);
Run Code Online (Sandbox Code Playgroud)
  1. 最后,在一行中,有一条单独的路径可以为您完成上述操作:

    从'chart.js/auto'导入图表;

  2. 通过导入和注册@Tatyana Molchanova 评论的所需部分

进口{图表,图表配置,线控制器,线元素,点元素,

LinearScale, Title} from 'chart.js' 
Run Code Online (Sandbox Code Playgroud)

然后在实例化新图表之前将其注册到组件中

Chart.register(LineController, LineElement, PointElement, LinearScale, Title);
Run Code Online (Sandbox Code Playgroud)

  • 刚刚测试!从“chart.js/auto”导入图表;就像魔术一样! (17认同)
  • 这全部记录在这里:https://www.chartjs.org/docs/latest/getting-started/integration.html#bundlers-webpack-rollup-etc (4认同)

Bob*_*sey 8

角度 12 在这里。Gaurev 的回答对我有用。我不得不使用:

import { Chart, registerables } from 'chart.js';
export class ChartTest {

  constructor() {
    Chart.register(...registerables);
  }

  // methods to actually make the chart per documentation
}
Run Code Online (Sandbox Code Playgroud)


Але*_*лёв 7

您会收到错误,因为您需要包含来自 Chart.js/auto 的 Chart,而不是来自 Chart.js:

\n
import { Chart } from \'chart.js/auto\'\n
Run Code Online (Sandbox Code Playgroud)\n

文档中明确指出了这一点:

\n

https://www.chartjs.org/docs/latest/getting-started/integration.html#helper-functions

\n

或者您需要像这样使用动态导入:

\n
const { Chart } = await import(\'chart.js\')\n
Run Code Online (Sandbox Code Playgroud)\n

https://www.chartjs.org/docs/latest/getting-started/integration.html#commonjs

\n

*检查版本 ^4 \xd0\xa1hart.js

\n