RXjs groupBy - Group AngularFire Firestore collection

拜拜、爱过 提交于 2019-12-11 15:29:40

问题


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:


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


来源:https://stackoverflow.com/questions/48190224/rxjs-groupby-group-angularfire-firestore-collection

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