1👍
Your code has a few issues, here the two I could spot:
-
the Main error ocurres because chartjs expects a object array for the property
dataset
, so in your case you would have to change your code to something like this:this.lineBar = new Chart(this.linePresents.nativeElement, { type: 'line', data: { labels: this.lineBarLabels, datasets: [{data: this.lineBarValue}] } });
-
The array
this.lineBarLabels
is never set (will be a empty array), you would have to change:this.lineBarLabels.includes(element.date);
tothis.lineBarLabels.push(element.date);
These are the main issues, I don’t understand what output should you are looking for, and I don’t think that setting the values to strings value_time_formatted
will work, but if you fix the above mentioned points, you will be a step closer to a working chart.
Update:
It seems you fixed on mistake in your question, if you want to improve your code here is a tip for you time convertion (link to relevant documentation):
const date = new Date();
// A cleaner solution
let aShortWay = date.toISOString().substring(11,23);
// Your Sode: Not really readable, and pretty long
let yourCode = (date.getUTCHours() ? (date.getUTCHours() > 9 ? date.getUTCHours() : '0' + date.getUTCHours()) : '00') + ':' +
(date.getUTCMinutes() ? (date.getUTCMinutes() > 9 ? date.getUTCMinutes() : '0' + date.getUTCMinutes()) : '00') + ':' +
(date.getUTCSeconds() ? (date.getUTCSeconds() > 9 ? date.getUTCSeconds() : '0' + date.getUTCSeconds()) : '00') + '.' +
(date.getUTCMilliseconds() > 99 ? date.getUTCMilliseconds() : date.getUTCMilliseconds() > 9 ? '0' + date.getUTCMilliseconds() : '00' + date.getUTCMilliseconds());
console.info(`aShortWay Time:${aShortWay}`)
console.info(`yourCode Time:${yourCode}`)
- [Chartjs]-ChartJs chart won't update new values
- [Chartjs]-How to disable default label for a particular dataset chart js
0👍
I finally find a solution, hope that someone will use it in the right way 🙂
After this part of the code:
res.measurements.forEach(element => { this.lineBarLabels.push(element.date); this.lineBarValue.push(element.value_time_formatted); }); this.createLineChart();
I made this createLineChart() method to parse and render the chart:
public createLineChart() {
this.lineBar = new Chart(this.linePresents.nativeElement, {
type: 'line',
data: {
labels: this.lineBarLabels,
datasets: [{label: this.translate.instant('time'), data: this.lineBarValue, fill: false}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
ticks: {
callback: function (value) {
const date = new Date(Number(value) * 1000);
return date.toISOString().substring(11,23);
}
}
}
},
plugins: {
tooltip: {
callbacks: {
label: function (context) {
const date = new Date(Number(context.formattedValue) * 1000);
return date.toISOString().substring(11,23);
}
}
}
}
}
}
);
this.lineBar.update();
}