Working with angular 7 alongside the chart.js library has been quite interesting. I managed to create a line chart using data pulled from the firebase realtime database via the angularfire2 library.
The chart currently displays the number of messages sent per hour, but my goal is to have it update in real-time as new data comes in.
Below you'll find the code for the static version. Any advice on how to achieve real-time updating would be much appreciated.
<div style="display: block;padding-top:30px">
<canvas baseChart
[chartType]="'line'"
[datasets]="chartData"
[colors]="colors"
[labels]="chartLabels"
[options]="chartOptions"
[legend]="true">
</canvas>
</div>
And here's the .ts file:
@ViewChild(BaseChartDirective, null)
public chart: BaseChartDirective;
chartOptions = {
responsive: true,
legend: {
display: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
chartData = [
{ data: [], label: 'Messages/hour'
}
];
colors = []
chartLabels = [];
async ngOnInit() {
let resp = await this.dataSvc.fetchHourlyMessages(this.core.orgName)
for(let key of Object.keys(resp)){
this.chartData[0].data.push(resp[key].messages)
let hour = resp[key].hour
this.chartLabels.push(hour)
}
this.chart.chart.update()
}
This is the service used:
fetchHourlyMessages(orgName:string){
return new Promise((resolve, reject) =>
{
this.db.list(orgName + '/stats/messages/hourly/', ref => ref.orderByChild("messages").limitToLast(12)).valueChanges().subscribe(
(res) => {
resolve(res)},
(err) => {
console.log("hitting error:" + err); reject(err)
}
)
})
}
The structure of the data is as follows:
/stats
/messages
/hourly
/1pm
messages: 3
hour: 1pm
/2pm
messages: 4
hour: 2pm