gpt4 book ai didi

node.js - 如何在 Angular 2 和 Node JS 中更新 ng2-chartjs2 图表中的数据

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:33 25 4
gpt4 key购买 nike

我正在使用 NodeJS、Angular2 和 ng2-chartjs2。下面我列出了渲染图表的代码的相关部分。数据使用固定日期范围从 API 加载到 this.data 中。我想允许用户选择一个日期范围,然后更新图表。来自 here我知道您可以在图表对象上调用 update() 来更新其中的数据,但我不知道如何获取图表对象,因为组件代码实际上从未引用它 - 它已经完成渲染模板时自动进行。看着source code (第 13 行)我看到作者打算让该对象可用。我联系了作者,但尚未收到回复,需要采取行动。我已经了解了很多关于 Angular2 的知识,但还不是专家,所以也许对 Angular2 更深入的了解会让这一点变得显而易见。我怎样才能访问对象并对其调用 update() ,或者以其他干净的方式进行操作?

模板包含

    <chart [options]="simple.options"></chart>

并且组件 typescript 代码包含

import { ChartComponent } from 'ng2-chartjs2';
...

@Component({
selector: 'home',
templateUrl: 'client/components/home/home.component.html',
styleUrls: ['client/components/home/home.component.css'],
directives: [DashboardLayoutComponent, CORE_DIRECTIVES, ChartComponent],
pipes: [AddCommasPipe],
})

...

setCurrentSimpleChart = (simpleType: number): void => {
this.simple.options = {
type: 'line',
options: this.globalOptions,
data: {
labels: this.data[simpleType].labels,
datasets: [{
label: this.titles[simpleType],
data: this.data[simpleType].data,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}],
},
};

...
}

更新:如果这对任何人有帮助:我实际上在页面上有两个不同的图表,所以我根据接受的答案进行了谷歌搜索并找到了 ViewChildren ,并将它们映射到不同的变量,这样我就可以分别更新它们,使用

[this.simpleChart, this.liftChart] = this.chartComponents.toArray().map(component => component.chart);

(另请注意,这是使用 angular2 的 rc - 从那时起指令等已从组件本身中移出。)

最佳答案

您可以使用ViewChild来保存对组件的引用:

@ViewChild(ChartComponent) chartComp;

然后就可以得到chart对象:

let chart = this.chartComp.chart;

这是corresponding plunker

关于node.js - 如何在 Angular 2 和 Node JS 中更新 ng2-chartjs2 图表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38771229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com