Angular Firestore combineLatest with multiple queries

故事扮演 提交于 2020-04-18 03:57:39

问题


I'm having a little trouble with Angular9, Firestore6 and the combineLatest rxjs operator.

I have one collection of users, and another collection of items. One user can have several items, but in an old fashioned manyToMany relationship way, in which the items are master data (non modifiable) and the bridge table joins both collections with additional data:

  • items

    • apple
      • name: "apple"
      • color: "green"
  • user

    • items
      • uid
        • uid: "apple"
        • quantity: 23

So I need to get a list of the items of the logged in user, joining both collections:

  • user
    • items
      • uid
        • uid: "apple"
        • quantity: 23
        • join
          • name: "apple"
          • color: "green"

This is my code:

import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore } from '@angular/fire/firestore';
import { switchMap, map } from 'rxjs/operators';
import { combineLatest, of } from 'rxjs';

getUserItems() {
  return this.angularFireAuth.authState.pipe(
    switchMap(user => {
      if (user) {
        return this.angularFirestore.collection<any>(`users/${user.uid}/items`).valueChanges()
          .pipe(
            switchMap(userItems=> {
              return combineLatest([
                of(userItems),
                userItems.map(userItem=> this.angularFirestore.doc<any>(`items/${userItem}`).valueChanges())
              ])
            }),
            map(([userItems, items]) => {
              console.log(userItems, items);
              return userItems.map(userItem => {
                return {
                  ...userItem,
                  join: items.find(item => item.uid === userItem.uid)
                }
              })
            })
          )
      }
    })
  )
}

But in the map(([userItems, items]), instead of [any[], any[]], I get [any[], Observable<any>], it does not compile because Property 'find' does not exist on type 'Observable<any>'.

I guess it's because the second .valueChanges() is not getting resolved, but I don't know what I'm doing wrong. Can anyone help me out?

I already tried other answers like this one but with no luck so far.

Thanks in advance.


回答1:


You were very close, you just need to add a spread operator to the userItems.map and you need to get the itemId (just a guess) from the userItem object:

return combineLatest([
  of(userItems),
  ...userItems.map(
    userItem => this.angularFirestore.doc<any(`items/${userItem.itemId}`).valueChanges()
  )
])


来源:https://stackoverflow.com/questions/61276861/angular-firestore-combinelatest-with-multiple-queries

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