AngularFire2 group data into array of objects Firestore collection

╄→гoц情女王★ 提交于 2019-12-11 15:52:33

问题


I have a collection called addons. The collection contains fields namely, name, desc, price and type.

I am straight away fetching the data with this.afs.collection<AddOns>('addons'); which returns AngularFirestoreCollection<AddOns>. I have below class file defined for data from Firestore Collection.

AddOns.ts

export class AddOns{
    name?: string;
    desc?: string;
    price?: number;
    type?: string;
}

export class AddOnId extends AddOns{
    aid?: string;
}

Since I need metadata too from that collection I have created AddOnId class which extends AddOns class. To get all the data I do it as below:

addOnsList: Observable<AddOnId[]>;

this.addOnsList = this.afs.collection<AddOns>('addons').snapshotChanges().map( x => {
  return x.map(data => {
    const addon = data.payload.doc.data() as AddOns;
    const aid = data.payload.doc.id;
    return {aid, ... addon}
  });
})

This post has mentioned the problem of unable to use groupby since data that will be returned is Observable of Array and also has an answer how to convert Observable of array to Observable of values using flatMap.

I then tried

const grouped = this.afs.collection<AddOns>('addons').snapshotChanges()
                    .flatMap( arr => Observable.from(arr))
                    .groupBy(d => d.payload.doc.data().type);

But even that does not return desired result. How else can I achieve this? How should I be grouping the data based on their type and turn it into an Observable of values?


回答1:


Do the grouping inside the Observable map, e.g, return x.map { ... }.groupBy { ... } Since you intend to transform the data, not the Observable itself. lodash has a good implementation of groupBy for an array.



来源:https://stackoverflow.com/questions/49248935/angularfire2-group-data-into-array-of-objects-firestore-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!