0👍
All of your code is inside the for
loop and is being executed five times. So four charts are being created and destroyed with only the fifth one being displayed.
Move your chart creation code outside of the for
loop, something like this:
const series = [],
counts = [];
for (let Data of Post) {
series.push(Data.Status);
counts.push(Data.Count);
}
this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {
type: "doughnut",
data: {
labels: series,
datasets: [{
label: 'Completed',
data: counts,
}]
}
})
Note that I haven’t run this code so there may be a typo, but it shows the concept of what you need to change to fix the problem. (Next time please post your data as text, not a screenshot. Then I could have built a working example here.)
0👍
You need to extract the labels and data from the response. You could remove the for
loop and use map()
:
series = this.Post.map(item => Number(item.Count));
labels = this.Post.map(item => item.Status);
Notice the Number
cast for item.Count
. It is needed since the response from the API is of string type and the chart only accepts data as a numbers array.
Also you do not need to define label: 'Completed'
property inside datasets
since it is defined using labels
property. Try the following
this.api.getPerformancePie(username, password).subscribe( Post => {
const series = Post.map(item => Number(item.Count));
const labels = Post.map(item => item.Status);
this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {
type: 'doughnut',
data: {
labels: labels,
datasets: [
{
data: series,
backgroundColor: ['red', 'blue', 'green', 'yellow', 'turquoise']
},
]
}
});
}
Working example: Stackblitz