I am trying to grab info saved to firebase and use it dynamically to populate an array for ng2-chart.
The problem I currently have is that the observable does not allow me to populate this array.
getEntries(id) {
this.entries2 = this.dataService.getEntries(id);
let datesarr: string[] = [];
let arr = [];
this.dataService.getEntries(id).subscribe((entry) => {
entry.forEach(function (x) {
arr.push(x);
});
for (let i = 0; i < arr.length; i) {
// console.log(arr[i].Q1);
let x: string = arr[i].Q1;
// console.log(x);
datesarr.push(x);
//this.barChartLabels.push(x);
//Whenever I try to push this value it encounters an error.
}
});
}
Am I mis-using the subscribe function for this observable? If so, how can I fix it?
Previously I attempted to use the following snippet:
getEntries(id) {
this.entries2 = this.dataService.getEntries(id);
let arr = [];
let datesarr: string[] = [];
this.entries2.forEach(function (entry) {
entry.forEach(function (x) {
arr.push(x);
});
for (let i = 0; i < arr.length; i) {
let x: string = arr[i].Q1;
datesarr.push(x);
//this.barChartLabels.push(x);
}
});
I believe the issue is that this observable is async and the barchartlabels line pushes "undefined" instead of any real data.
entries2 is defined as:
entries2: Observable<any>;
barchartlabels is just an empty array I am trying to push data to:
public barChartLabels: Label[] = [];
And the code for grabbing the info from the db in dataService is:
getEntries(id){
return this.db.collection(`users/${id}/entries`).valueChanges();
}
Could someone please point me in the right direction as to how to tackle this problem?
Note: I've tried looking into Subjects, but am not sure if they fit into my code as returning the last value of a stream doesn't seem to be all too useful.
CodePudding user response:
It appears to be a Type problem. this.barChartLabels expects an Array of Label as you pointed
this.barChartLabels: Label[] = [];
So you just try to cast the x data to Label:
getEntries(id) {
this.entries2 = this.dataService.getEntries(id);
let datesarr: string[] = [];
let arr = [];
this.dataService.getEntries(id).subscribe((entry) => {
entry.forEach(function (x) {
arr.push(x);
});
for (let i = 0; i < arr.length; i) {
// console.log(arr[i].Q1);
let x: string = arr[i].Q1;
// console.log(x);
datesarr.push(x);
this.barChartLabels.push(x as Label); // note as Label
}
});
}