RXjs groupBy - Group AngularFire Firestore collect

2019-08-26 04:38发布

I'm trying to group a AngularFire Firestore Collection (Observable[]) by a field, say userId.

I have a collection of items, each with varying userId values, and I need to group them into a multidimensional array. So, convert..

[ 
  {userID:1, color:'blue' }, 
  {userId:2, color:'green'}, 
  {userId:1, color:'orange'}
]

into

[ 
  [
   {userID:1, color:'blue' }, 
   {userId:1, color:'orange'}
  ],
  [
   {userId:2, color:'green'}
  ]
]

I'm totally new to RxJs, I get how the groupBy operator works when making an Observable.of(itemsArray), but I can't see how to get this to work with the Observable returned from AgularFire

let items:Observable[] = this.afs.collection<Item>('items')
  .snapshotChanges()
  .groupBy( item => item.userId ); //item is actually the array

It looks like AngularFire returns an Observable that emits the Array as a whole, not each element.

If I map it, dont I then just have each item in the array, and cant use the groupBy?

Any pointers on how to return a Observable array of grouped arrays as per above?

1条回答
神经病院院长
2楼-- · 2019-08-26 05:16

You can simply turn your observable of array into an observable of the values of the array with:

myObservable.flatMap(arr => Rx.Observable.from(arr));
查看更多
登录 后发表回答