首页 > 解决方案 > Chart.js 注释工作但在 Angular 5 中导致控制台错误

问题描述

我有一个基于接收到的数据的动态图表生成组件。我在组件内创建一个图表实例并填写属性。我将 chartjs-annotate-plugin 导入为

import * as annotation from 'chartjs-plugin-annotation'; 

并像这样注册图表插件:

constructor() {
   Chart.pluginService.register(annotation);
} 

我试图在图表实例化之前移动它,但有趣的是,虽然我确实看到了注释,但它也会导致控制台错误,指出注释不是 ChartOptions 上的属性:

ERROR in src/app/shared/charts/chart/chart.component.ts(143,11): error 
  TS2345: Argument of type '{ plugins: any[]; type: string; data: { labels: 
  any[]; datasets: any[]; }; options: { scales: { y...' is not assignable to 
  parameter of type 'ChartConfiguration'.
  Types of property 'options' are incompatible.
  Type '{ scales: { yAxes: { stacked: boolean; ticks: { beginAtZero: true; 
  callback: (value: any, index: ...' is not assignable to type 
 'ChartOptions'.
Object literal may only specify known properties, and 'annotation' does 
not exist in type 'ChartOptions'.

有任何想法吗?

从赏金编辑:不是OP 的代码,但这里有一些代码可以重现 Angular 8 和 ChartJS Annotation 插件 0.5.7 中的问题:

let annotation = [];

annotation.push({
        drawTime: 'beforeDatasetsDraw',
        type: 'box',
        xMin: i - 1, //index + 1,
        xMax: i + 1, //index + 5,
        yMin: this.yValues.reduce((a, b) => Math.min(a, b)).toString(),
        yMax: this.yValues.reduce((a, b) => Math.max(a, b)).toString(),
        // ID of the X scale to bind onto
        xScaleID: 'x-axis-0',

        // ID of the Y scale to bind onto
        yScaleID: 'y-axis-0',
        backgroundColor: 'rgba(101, 33, 171, 0.15)',
        borderColor: 'rgba(101, 33, 171, 0.5)',
        borderWidth: 2,
      });

let namedChartAnnotation = ChartAnnotation;
Chart.pluginService.register(namedChartAnnotation);

return new Chart('histogram' + number, {
  type: 'bar',
  data: {
    labels: this.xValues,
    datasets: [
      {
        label: 'Number of alerts',
        data: this.yValues,
      },
    ],
  },
  options: {
     annotation: {
        annotations: annotation,
     }
  }
});

使用此代码,我在控制台中得到了上面指定的错误,但它按预期工作。如果我将annotation:部分移动到plugins:,错误消失,但注释不再显示:

....
options: {
   plugins: {
      annotation: {
         annotations: annotation,
      },
   }
}

标签: angulartypescriptchart.jschartjs-plugin-annotation

解决方案


推荐阅读