问题
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"
- apple
user
- items
- uid
- uid: "apple"
- quantity: 23
- uid
- items
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"
- uid
- items
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