I am working with an API that returns a JSON object like this:
{
"triggerCount": {
"ignition_state_off": 16,
"ignition_state_on": 14,
"exit_an_area": 12,
"enter_an_area": 19,
"door_unlocked": 1,
"door_locked": 1,
"fuel_level_below": 12
}
}
The response is obtained using the following service :
interface ITrigger{
triggerCount: ITriggerCount;
}
interface ITriggerCount{
[key:string]: number;
}
@Injectable()
export class DbApiService {
private triggersUrl = 'http://localhost:3000/triggers';
constructor(private http: HttpClient) {
}
getTriggerCount(){
return this.http.get<ITrigger>(this.triggersUrl)
}
}
Component where the service is injected:
export class TriggersComponent implements OnInit {
@Input() triggerCountChart = [];
triggers:any;
tempArray: any = [];
constructor(private triggerService: DbApiService) { }
ngOnInit() {
this.getTriggerCount()
this.buildChart()
}
getTriggerCount(){
this.triggerService.getTriggerCount().subscribe(data =>{this.triggers = data;
this.tempArray = this.triggers.triggerCount;
console.log(this.triggers,this.tempArray);
} );
}
I log the response results to check the data, screenshot here :
https://i.sstatic.net/RHbSO.png
In order to render a chart, I need to extract attribute strings like ignition_state_off
and save them in a string array along with their corresponding values in a number array.
Chart Function
The chart currently uses manually inserted data. Here's the function:
buildChart(){
let triggerLabels = ['ignition_off','ignition_on','enter-area','exit-area','door_unlocked','door_locked','fuel_drop'];
let triggerCountArray = [12,13,22,32,14,8,17]
this.triggerCountChart = new Chart('canvas-triggers', {
type: 'pie',
data: {
labels: triggerLabels,
datasets: [
{
data: triggerCountArray,
// borderColor: "#3cba9f",
backgroundColor: ["#e8f1f2","#b9c0c1","#8d99ae","#3283a9","#006494","#283c4e"],
fill: false
},
]
},
options: {
title: {
display: true,
text: 'applets created in percentage',
fontSize:14
},
legend: {
display: true,
position: "right",
labels: {
boxWidth : 40,
fontSize : 14
}
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}],
}
}
});
}
I need help to properly extract and use the API response for the chart. Thank you!