I'm trying to update a dashboard with responses from HTTP requests I make, but even though the data is correctly fetched from the API, it doesn't update the chart.
The component is like this:
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { DataService } from 'src/app/services/data.service';
import { ChartData } from 'angular-morris-js';
import * as Chart from 'chart.js';
@Component({
selector: 'app-component',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
@ViewChild('donutChart1', {static: false}) donutChart1Ref: ElementRef;
donutChart: Chart;
constructor(
private dataService: DataService
) {}
donutChartData: ChartData[] = [];
public donutChartOptions = {
colors : ['rgba(218,142,26,0.61)', 'rgba(10,82,166,0.72)', 'rgba(218,26,212,0.61)']
};
ngOnInit() {
this.loadChartData();
}
loadChartData() {
this.dataService.getData().subscribe(
(response: any) => {
const dataGroup1 = response.body.dataOne;
const dataGroup2 = response.body.dataTwo;
this.donutChartData.push({
label: 'Group 1',
value: dataGroup1
});
this.donutChartData.push({
label: 'Group 2',
value: dataGroup2
});
const ctx = this.donutChart1Ref.nativeElement.getContext('2d');
this.donutChart = new Chart(ctx, null);
}
);
}
async red() {
}
}
HTML code:
<div class="col-md-12 center-flex-column" id="donutChart1" mk-morris-js
[data]="donutChartData" [options]="donutChartOptions" size=100
type="Donut"
></div>
(requested by @yong-shun) The response that comes from the API is like this:
{
"dataOne": 234,
"dataTwo": 5346
}
I'm new to Angular, so if anyone can explain why this is happening and how to fix it, it'll be very appreciated. Thanks in advance.
Turns out that just overwriting the property does the trick:
loadChartData() {
this.dataService.getData().subscribe(
(response: any) => {
const dataGroup1 = response.body.dataOne;
const dataGroup2 = response.body.dataTwo;
this.donutChartData = [
{
label: 'Group 1',
value: dataGroup1
},
{
label: 'Group 2',
value: dataGroup2
},
]
}
);
}
I'm using angular-morris-js
so it basically takes care of the update automatically. Hope that this helps another devs too.