typescript - ng2-charts 和注解插件:数据更新后注解不可见
问题描述
我正在使用ng2-charts库创建一个使用来自 REST API 的数据进行更新的图表。我使用注释插件。注释的数量发生了变化,因此更改现有的注释是不够的——我需要能够在运行时添加/删除新的注释。
当我在开始时向图形选项添加注释时,注释呈现得很好。但是在运行时,更新数据和更新选项对象后,看不到任何注解。
稍后,我在图表的选项中添加注释:
this.barChartOptions.annotation.annotations.push(
{
drawTime: 'beforeDatasetsDraw',
type: 'box',
xScaleID: 'x-axis-0',
yScaleID: 'y-axis-0',
xMin: tmpFirstBorder,
xMax: tmpLastBorder,
yMin: 0.5,
yMax: 5,
backgroundColor: 'rgba(71, 158, 245, 0.5)',
borderColor: 'rgb(71,158,245)',
onClick: function (e) {
console.log('Box', e.type, this);
}
}
然后更新数据,以便重新绘制图表:
this.barChartOptions = this.barChartOptions;
this.barChartData = tempChartData;
图表被重新绘制得很好,但没有注释。
我认为这可能是图表选项没有更新的问题,所以我尝试添加一个显式更新:
@ViewChild(BaseChartDirective) chart: BaseChartDirective;
[...]
this.chart.chart.update();
但无济于事。
有谁知道我如何正确绘制注释?谢谢。
解决方案
this.barChartOptions.annotation.annotations
不是数组。这是示例中的另一个对象
const options = {
plugins: {
autocolors: false,
annotation: {
annotations: {
line1: {
type: 'line',
yMin: 60,
yMax: 60,
borderColor: 'rgb(255, 99, 132)',
borderWidth: 2,
}
}
}
}
};
所以要添加一个新的注解,你需要添加一个对象而不是推送一个数组元素。例如,您可以获得对象中已有的注释数量
let annotationsCount = Object.entries(this.barChartOptions.annotation.annotations)
然后你可以添加一个新元素
this.barChartOptions.annotation.annotations[annotationsCount] = yourNewAnnotationObject
annotationCount可以是任何东西。它只是示例中的line1之类的新对象的键使用内部已有对象的数量只是一个建议。但它必须是唯一的,否则你会覆盖现有的而不是添加新的
推荐阅读
- c++ - 如何使用 gdb 调试 g++ 分段错误?
- python - 处理列名中的括号
- python - Seaborn 图在 ipython 单元格中显示乱序
- php - 我的分页在 wordpress 自定义主题中不起作用
- sql - 如果在 Hive SQL 中找不到匹配项,则提供要加入的备用列
- c# - ASP 核心 API 2.2。RequireClaim 和 RequireAuthenticatedUser 策略不起作用
- ruby - Rails request.referer 没有重定向到上一个 url
- re2 - 如何匹配任何不包含 Re2 中特定单词的字符串
- jquery - 确定是按月付款还是按年付款
- powershell - 如何通过 Caml 克服 SharePoint Online 5000 行限制?