AngularFire2 将数据分组到 Firestore 集合的对象数组中 [英] AngularFire2 group data into array of objects Firestore collection
问题描述
我有一个名为 addons
的集合.该集合包含字段,即 name
、desc
、price
和 type
.
I have a collection called addons
. The collection contains fields namely, name
, desc
, price
and type
.
我立即使用 this.afs.collection
获取数据,它返回 AngularFirestoreCollection
.我为 Firestore 集合中的 data
定义了以下类文件.
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;
}
因为我也需要该集合中的元数据,所以我创建了扩展 AddOns
类的 AddOnId
类.要获取所有数据,我按如下方式执行:
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}
});
})
这篇文章已经提到了无法使用groupby
的问题,因为返回的数据是Observable of Array
,还有一个答案如何转换Observable of array
到 Observable of values
使用 flatMap
.
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
.
然后我尝试了
const grouped = this.afs.collection<AddOns>('addons').snapshotChanges()
.flatMap( arr => Observable.from(arr))
.groupBy(d => d.payload.doc.data().type);
但即使这样也不会返回所需的结果.我还能如何实现这一目标?我应该如何根据数据类型对数据进行分组并将其转换为 Observable 值?
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?
推荐答案
在 Observable 地图内部进行分组,例如,return x.map { ... }.groupBy { ... }
由于您打算转换数据,而不是 Observable 本身.lodash 对数组有一个很好的 groupBy 实现.
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.
这篇关于AngularFire2 将数据分组到 Firestore 集合的对象数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!