【发布时间】:2021-06-13 04:02:37
【问题描述】:
我正在尝试使用 chart.js 和 chartjs-plugin-streaming 将数据流式传输到画布中。 它使用随机数据完美地工作。但是如何流式传输我的自定义数据?
流式传输随机数据效果很好(每 2 秒更新一次)。
tab1.page.html
<div>
<canvas
baseChart
[chartType]="'line'"
[datasets]="datasets"
[options]="options">
</canvas>
</div>
tab2.page.ts
import { Component } from '@angular/core';
import 'chartjs-plugin-streaming';
@Component({
selector: 'app-tab2',
templateUrl: 'tab2.page.html',
styleUrls: ['tab2.page.scss']
})
export class Tab2Page {
datasets: any[] = [{
data: []
}, {
data: []
}];
options: any = {
scales: {
xAxes: [{
type: 'realtime',
realtime: {
onRefresh: function(chart: any) {
chart.data.datasets.forEach(function(dataset: any) {
dataset.data.push({
x: Date.now(),
y: Math.random() * 100
});
});
},
delay: 2000
}
}],
yAxes: [{
ticks: {
max:100,
min:0
}
}]
}
};
}
但是当我尝试流式传输我的数据时,它会抛出一个错误提示
ERROR TypeError: Cannot read property 'myDataFromServer' of undefined
这是我的自定义代码,需要您的好评。
import { Component } from '@angular/core';
import 'chartjs-plugin-streaming';
@Component({
selector: 'app-tab2',
templateUrl: 'tab2.page.html',
styleUrls: ['tab2.page.scss']
})
export class Tab2Page {
myDataFromServer:number;
updateMyDataFromServerFunction:any;
datasets: any[] = [{
data: []
}, {
data: []
}];
options: any = {
scales: {
xAxes: [{
type: 'realtime',
realtime: {
onRefresh: function(chart: any) {
chart.data.datasets.forEach(function(dataset: any) {
dataset.data.push({
x: Date.now(),
y:this.myDataFromServer
});
});
},
delay: 2000
}
}],
yAxes: [{
ticks: {
max:100,
min:0
}
}]
}
};
constructor(
) {}
ngOnInit(){
this.updateMyDataFromServer()
}
updateMyDataFromServer(){
console.log('updateMyDataFromServer() called');
this.updateMyDataFromServerFunction = setInterval(() => {
this.myDataFromServer = Math.random() * 100
},1000)
}
}
【问题讨论】:
标签: javascript angular typescript ionic-framework chart.js