AngularFire2将数据分组到Firestore对象数组中 [英] AngularFire2 group data into array of objects Firestore collection

查看:60
本文介绍了AngularFire2将数据分组到Firestore对象数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为addons的集合.集合包含的字段分别为namedescpricetype.

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

我立即用this.afs.collection<AddOns>('addons');获取数据,该数据返回AngularFirestoreCollection<AddOns>.我在下面为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;
}

由于我也需要该集合中的元数据,因此我创建了AddOnId类,该类扩展了AddOns类.要获取所有数据,请按以下步骤操作:

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,并且还提供了一个答案,该答案如何使用flatMapObservable of array转换为Observable of values.

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);

但是即使那样也不能返回期望的结果.我还能怎么实现呢?我应该如何根据数据的类型对数据进行分组并将其转换为可观察的值?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆