I am trying to get all the data from firestore
- collection
and subcollection
into an observable
form of array
and display it with async
pipe.
availableCategoriesCollection: AngularFirestoreCollection<Category>;
availableCategories$: Observable<CategoryId[]>;
lstCategories: Observable<any>;
this.availableCategoriesCollection = this.httpDataService.getAllCategories();
this.availableCategories$ = this.availableCategoriesCollection.snapshotChanges().map(data => {
return data.map(record => {
const rec = record.payload.doc.data() as Category;
const cId = record.payload.doc.id;
return {cId, ...rec};
});
});
this.lstCategories = this.availableCategories$.mergeMap(data => {
const observables = data.map((rec: CategoryId) => {
if (rec.hasSubCat) {
return this.httpDataService.getSubCategory(rec.cId).snapshotChanges().map(d => {
return d.map(r => {
const arr: any = {};
arr.id = r.payload.doc.id;
arr.itemName = (r.payload.doc.data() as Category).categoryName;
arr.category = rec.categoryName;
return Observable.of(arr);
});
});
}else {
const arr: any = {};
arr.id = rec.id;
arr.itemName = rec.categoryName;
arr.category = 'All';
return Observable.of(arr);
}
});
return Observable.forkJoin(observables);
});
and I've used <pre>{{lstCategories | async | json}}</pre>
to display the data, but it is always null.
When I console.log(observables)
before forkJoin
I get (9) [ScalarObservable, Observable, Observable, ScalarObservable, ScalarObservable, ScalarObservable, ScalarObservable, ScalarObservable, Observable]
out of which 3 of them which are Observable
are subcategories and 6 of them which are ScalarObservable
are main categories.
In spite of this data, the lstCategories doesn't get updated via async
.
I've also tried to subscribe to lstCategories
like
this.lstCategories.subscribe(data => {
console.log(data);
});
but the above log never happens which means it is not getting subscribed. My knowledge on rxjs
is very weak. Hope to find some help here.
When you use map, you transform the response of a request. You needn't return an Observalbe
Try this way
It seems that you are returning
Observable
ofObservable
of some array at following code blockThis block is already inside a map function of an Observable. When you return another Observable your whole return object looks like
Observable<Observable<any[]>>
Just change return line toreturn arr;