I am trying to stream data into canvas with chart.js and chartjs-plugin-streaming. It works perfectly using random data. But how can I stream my custom data ?
Streaming random data works well(updating every 2 seconds).
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
}
}]
}
};
}
But when I try to stream my data it throws an error saying
ERROR TypeError: Cannot read property 'myDataFromServer' of undefined
This is custom my code that needs your kind reviews.
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)
}
}
