I am trying to render a live CanvasJs chart using Angular 4. I can successfully render the chart and get my data from my api. However, I am struggling to update the chart with new data (every second).
With all the documentation that I read you should render the chart every time you update the data. I am assuming that is what I am doing, but it isn’t working.
Any help would be appreciated.
Here is my code:
ngOnInit() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
let body = {
"returnImmediately": true,
"maxMessages": 1
};
let chart = new CanvasJS.Chart("chartContainer-Australia", {
title: {
text: "Live Data"
},
axisX: {
title: "Axis X Title"
},
axisY: {
title: "Units"
},
data: [{
type: "line",
dataPoints: this.tc1
}]
});
chart.render();
console.log('chart rendered');
return Observable.concat(Observable.of(null), IntervalObservable.create(1000))
.flatMap(() => this.http.post(this.dataUrl, JSON.stringify(body), options))
.map(
(res: Response) => res.json()
).subscribe(
(res) => {
// console.log("VALUE RECEIVED: ",res);
if (res.receivedMessages){
for (let i=0; i<res.receivedMessages.length; i++){
const data = atob(res.receivedMessages[i].message.data);
const dataParsed = JSON.parse(data);
const ack = res.receivedMessages[i].ackId;
this.dataArray.push({'sensorName': dataParsed.sensor['sensor-name'], 'value': dataParsed.sensor['value'], 'time': dataParsed.sensor['timestamp'], 'units': dataParsed.sensor['units']});
if (dataParsed.sensor['sensor-name'] == 'TC1') {
const temp = dataParsed.sensor['value'];
const time = dataParsed.sensor['timestamp'];
this.tc1.push({'y': temp, 'x': time});
chart.render();
console.log('tc1 chart rendered');
console.log('TC1: ', this.tc1);
}
}
}
},
(x) => {
/* this function is executed when there's an ERROR */
console.log("ERROR: "+x);
},
() => {
/* this function is executed when the observable ends (completes) its stream */
console.log("Completed");
}
);
}