Struggling to make sense of this dilemma, I find myself unable to crack the code. The data retrieved from my API is structured in the following format:
"data": [
{
"sr_count": 91,
"month_name": "October",
"month_num": 10,
"year": 2017
},
{
"sr_count": 50,
"month_name": "September",
"month_num": 9,
"year": 2017
}
]
I am required to extract the data from "sr_count" and "month_name" and reformat them into their own arrays for chart.js integration.
For example:
["91","50"]
["October", "September"]
The reportService fetches data from the API as shown below:
getSR(groupBy: string, beginDate:string, endDate:string): Observable<Report[]> {
return this.http.get(`${this.reportUrl}/SR?group_by="${groupBy}"&begin_date="${beginDate}"&end_date="${endDate}"`)
.map(res => res.json().data)
.catch(this.handleError);
}
In an attempt to process the data in my component code, I realized that mapping the data from sr_count
and month_name
into separate arrays might be the way forward. These arrays could then be pushed into local variables for utilization in chart.js
export class SrReportsComponent implements OnInit {
monthName: [];
srCount1: [];
srCount2: [];
data: any;
ngOnInit() {
this.reportService.getSRLastMonth()
.subscribe(data => {
srCount= data.map(item => {
return item.sr_count
})
console.log(srCount) // ["October", "September"]
this.srCount2.push(srCount) // [["52", "41"]]
});
this.reportService.getSRThisMonth('Month',lastMonth,today)
.subscribe(data => {
monthName= data.map(item => {
return item.month_name
}
srCount= data.map(item => {
return item.sr_count
}
console.log(monthName) // ["October", "September"]
this.monthName.push(monthName) // [["October", "September"]]
this.srCount1.push(srCount) //[["91","50"]]
});
console.log(this.monthName)// [["October", "September"]]
this.data = {
labels: this.monthName, //returns []
datasets: [
{
label: 'First Dataset',
data: this.srCount1,
fill: false,
borderColor: '#4bc0c0'
},
{
label: 'Second Dataset',
data: this.srCount2,
fill: true,
borderColor: '#4ba0c0'
}
]
}
}
As using the push()
method seems to nest the array which chart.js fails to recognize. I attempted monthName[0]
, but it yielded undefined
in the console
What would be the most effective approach to transform the array received from the observable into a local variable for successful interaction with chart.js?