问题描述
我正在使用ng2-charts
在Angular应用程序中绘制条形图。在某些时候,我不得不在图表中添加静态线,因此我决定使用chartjs-plugin-annotation
。将这两个库连接在一起的方法尚不完善,但是经过一番摸索之后,我终于能够使它正常工作。
这是一个简约的demo。然而,尽管它在stackblitz上运行良好,但我的本地计算机上的IDE抱怨annotation
接口不能期望ChartOptions
:
public barChartOptions: ChartOptions = {
responsive: true,scales: {
yAxes: [{
display: true,ticks: {
suggestedMin: 0
}
}]
},// This whole section is underlined in red by IDE
annotation: {
drawTime: 'afterDatasetsDraw',annotations: [
{
type: 'line',...
编译器也是如此:
ERROR in src/app/calendar/calendar.component.ts(31,5): error TS2322: Type '{ responsive: true; scales: { yAxes: { display: true; ticks: { suggestedMin: number; }; }[]; }; annotation: { drawTime: string; annotations: { type: string; mode: string; scaleID: string; value: number; borderColor: string; borderDash: number[]; borderWidth: number; }[]; }; }' is not assignable to type 'ChartOptions'.
Object literal may only specify kNown properties,but 'annotation' does not exist in type 'ChartOptions'. Did you mean to write 'rotation'?
尽管此警告并不能阻止项目的编译,但看起来仍然不正确。
我检查了ChartOptions
中定义的node_modules/@types/chart.js/index.d.ts
,实际上,它没有annotation
(并且不应该,因为该接口是在{{1}中定义的) }库,谁也不应该对插件的细节一无所知):
chart.js
我试图将interface ChartOptions {
responsive?: boolean;
responsiveAnimationDuration?: number;
aspectRatio?: number;
maintainAspectRatio?: boolean;
events?: string[];
legendCallback?(chart: Chart): string;
onHover?(this: Chart,event: MouseEvent,activeElements: Array<{}>): any;
onClick?(event?: MouseEvent,activeElements?: Array<{}>): any;
onResize?(this: Chart,newSize: ChartSize): void;
title?: ChartTitleOptions;
legend?: ChartLegendOptions;
tooltips?: ChartTooltipOptions;
hover?: ChartHoverOptions;
animation?: ChartAnimationoptions;
elements?: ChartElementsOptions;
layout?: ChartLayoutoptions;
scale?: RadialLinearScale;
scales?: ChartScales | LinearScale | LogarithmicScale | TimeScale;
showLines?: boolean;
spanGaps?: boolean;
cutoutPercentage?: number;
circumference?: number;
rotation?: number;
devicePixelRatio?: number;
plugins?: ChartPluginsOptions;
}
部分重新放置在其他地方(chartjs-plugin-annotation
documentation说它应该在annotation
下,这很有意义),但是在所有其他位置都被忽略了。因此,最终,为了摆脱警告,我只是删除了plugins
部分-而不是这个:
: ChartOptions
我只是这样写的:
public barChartOptions: ChartOptions = {
这消除了警告,但看起来仍然不够整洁。有谁知道如何正确使用此插件?
解决方法
我差不多有同样的问题。我发现在chartjs-plugin-annotations
的{{1}}文件中,已弃用了 ChartOptions 接口的定义,该接口与index.d.tx
中定义的接口冲突。
因此,在ng2-charts
中进行更改
~/project-folder/node_modules/@types/chartjs-plugin-annotation/index.d.ts
对此
// Extend the types from chart.js
declare module 'chart.js' {
interface ChartOptions {
// This is deprecated on master (not released yet)
annotation?: ChartJsAnnotation.AnnotationConfig;
}
// This is the correct version on master (not released yet)
// interface ChartPluginsOptions {
// annotation?: ChartJsAnnotation.AnnotationConfig;
// }
const Annotation: ChartJsAnnotation.AnnotationStatic;
}
这样做为我消除了编译器错误。