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

标签 node.js charts typescript angular

我正在使用 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/

相关文章:

android - node-gcm 只发送消息给 1 个设备?

node.js - 未捕获的类型错误 : Cannot call a class as a function React

node.js - 如何在 Electron 应用程序中路径到图像文件?

iphone - 如何更改 mychart Shinobi Charts 上使用的 XAxis

javascript - Angular2 - 登录后重定向

TypeScript 错误找不到模块 'angularfire2/interfaces' ionic 3 angularfire2-offline

typescript - 使用 Object.keys() 时保留类型

node.js - nodemailer 附件不起作用

javascript - NVD3 图表响应问题

ios - 是否可以在 swift 中使用 ios-charts 逐个手动设置 lineChart 的 xAxis 值?