我ng2-charts
用来在我的 Angular 应用程序中绘制条形图。在某些时候,我不得不在我的图表中添加静态线条,我决定使用chartjs-plugin-annotation
. 将这两个库连接在一起没有很好的文档记录,但经过一番谷歌搜索后,我最终能够让它工作。
这是一个简约的演示。然而,虽然它在 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
(也不应该,因为这个接口是在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;
}
我试图将零件重新定位到annotation
其他地方(chartjs-plugin-annotation
文档说它应该在下面plugins
,这完全有意义),但在所有其他位置它只是被忽略了。所以最终,为了摆脱警告,我只是删除了: ChartOptions
部分 - 也就是说,而不是这个:
public barChartOptions: ChartOptions = {
我只写了这个:
public barChartOptions = {
这删除了警告,但它仍然看起来不够整洁。有谁知道如何正确使用这个插件?