Is it possible to use a chart with Angular that dynamically retrieves data from an API? I am able to get the data from the API in ngOnInit, but encounter difficulties assigning it to the chart.
Below is the component TS code :
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { PageTitleService } from '../../core/page-title/page-title.service';
import { TranslateService } from '@ngx-translate/core';
import { StatistiqueService } from 'app/service/statistique/statistique.service';
@Component({
selector: 'ms-charts',
templateUrl:'./statstypedemande-component.html',
styleUrls: ['./statstypedemande-component.scss'],
encapsulation: ViewEncapsulation.None
})
export class StatsTypeDemandeComponent implements OnInit {
stats: number[];
statistiques: [];
constructor(private pageTitleService: PageTitleService,
public translate: TranslateService,
private serviceStatistique : StatistiqueService) {}
ngOnInit() {
this.translate.get('Statistique des types de demandes').subscribe((res: string) => {
this.pageTitleService.setTitle(res);
});
this.serviceStatistique.getTest()
.subscribe(res => {
console.log(res);
this.stats = res;
console.log(this.stats);
})
}
// Doughnut
public doughnutChartLabels = ['Entreprise', 'Salarié', 'Particulier'];
public doughnutChartColors: any[] = [{ backgroundColor: ["#b8436d", "#00d9f9", "#a4c73c"] }];
//public doughnutChartData:number[] = [350, 450, 100];
public doughnutChartData:number[] = this.stats;
public doughnutChartType:string = 'doughnut';
}
Now, let's look at the Service :
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class StatistiqueService {
readonly rootURL = 'https://localhost:44319/api';
list : number[];
constructor(private http: HttpClient) { }
getTest()
{
return this.http.get(this.rootURL + '/Demande/StatsTypeDemande');
}
}
Last but not least, here is the Component HTML :
<!--Ng2 Charts-->
<div class="row">
<!-- Doughnut Chart -->
<div *ngFor="let a of stats">
{{ a }}
</div>
<div class="col-12 col-sm-6 col-md-6 col-lg-6">
<div class="chk-block">
<div class="chk-block-title">
<div class="d-flex justify-content-between">
<div class="d-flex align-items-start flex-row">
<h3>Statistique des types de demande</h3>
</div>
</div>
</div>
<div class="chk-block-content">
<canvas baseChart height="100" [data]="doughnutChartData" [options]="PieChartOptions" [colors]="doughnutChartColors" [chartType]="doughnutChartType" [labels]="doughnutChartLabels"></canvas>
</div>
</div>
</div>
</div>
<!-- Row Closed -->