我试图将两个可观测对象组合成一个可观测对象,这样我就可以使用这两个对象的信息。可观察的对象都是来自NoSQL数据库中两个不同集合的文档( Cloud数据库)。这两个集合共享一个值相同的字段(uid和partnerID)。我首先创建了一个查询来获取第一个可观察的对象,这个查询返回一个Observable<{Object1}[]>。如果我试图添加代码以获得第二个可观察对象并将其与现有的对象组合,我将得到一个Observable<Observable<{Object1 merged with Object2}>[]>。
如何确保生成的可观测性是由从数据库中提取的这两个对象的组合的对象组成的数组?
我的目标是在我的角度计划中使用组合的可观测对象。我正试图通过rxjs操作符来实现这一点。
这是我的服务中没有第二个可观察对象的函数:
queryMatches(fieldNameOfRole, boolValueOfAccepted) {
return this.authService.user$.pipe(
switchMap(user => {
return this.angularFirestore
.collection('matches', ref => ref.where(fieldNameOfRole, '==', user ? user.uid : '')
.where('accepted', '==', boolValueOfAccepted))
.snapshotChanges()
.pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Match;
const matchId = a.payload.doc.id;
return { matchId, ...data };
});
})
);
})
);
}这将产生以下返回:
(method) MatchStoreService.queryMatches(fieldNameOfRole: any, boolValueOfAccepted: any): Observable<{
initiatorID: string;
partnerID: string;
matchedOffer: string;
accepted: boolean;
id: string;
}[]>这就是我试图把它和第二个可观测的物体结合起来的方法:
queryMatches(fieldNameOfRole, boolValueOfAccepted) {
return this.authService.user$.pipe(
switchMap(user => {
return this.angularFirestore
.collection('matches', ref => ref.where(fieldNameOfRole, '==', user ? user.uid : '')
.where('accepted', '==', boolValueOfAccepted))
.snapshotChanges()
.pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Match;
const matchId = a.payload.doc.id;
return { matchId, ...data };
});
})
);
}),
map(matches => {
return matches.map(match => {
return this.userStoreService.getUserById(match.partnerID).pipe(
map(user => {
return { ...match, ...user };
})
);
});
})
);
}这将产生以下返回:
(method) MatchStoreService.queryMatches(fieldNameOfRole: any, boolValueOfAccepted: any): Observable<Observable<{
uid: string;
firstname: string;
lastname: string;
dateOfBirth: Date;
sex: string;
city: string;
activities: string[];
offers: string[];
mail?: string;
... 4 more ...;
matchId: string;
}>[]>更新
如何实现getUserById():
getUserById(uid) {
return this.angularFirestore
.collection<any>(`users`)
.doc<User>(uid).valueChanges();
}发布于 2019-03-26 18:50:00
只需像这样使用forkJoin操作符
map(matches => {
return combineLatest(matches.map(match => {
return this.userStoreService.getUserById(match.partnerID).pipe(
map(user => {
return { ...match, ...user };
})
);
}));
})https://stackoverflow.com/questions/55363729
复制相似问题