0
votes

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

1 Answers

0
votes

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.