我尝试为我的每个邮件文档获取用户。我们有:
users
user_id => user_data
message
msg_id => { message, user_id }
所以我尝试了(基于that answer):
getUserData(userId) {
const docRef = this.afs.collection('/users').doc(userId);
return docRef.ref.get();
}
getMsgs(topicId){
return this.afs.collection('/topics_msgs/' + topicId + "/comments").snapshotChanges().map(actions => {
return actions.map(a => {
const commentData = a.payload.doc.data();
this.getUserData(commentData.user_id).then(
user => {
return {user: user.data(), ...commentData};
}
);
});
});
}
和组件中:
this.firebaseService.getMsgs(this.id).subscribe( msgs => {
console.log(msgs);
this.messages = msgs;
})
但是当然不能用-内部映射不会在promise之外返回任何内容,因此组件会收到undefined
的列表。
我对如何处理这个问题有些困惑。谢谢你。
答案 0 :(得分:1)
使用高阶可观察值将数据转换为适合您需要的类型。关于您的问题(据我了解),您可以执行以下操作:
getUserData(userId): Observable<UserData> {
const docRef = this.afs.collection('/users').doc(userId);
return docRef.snapshotChanges().pipe(
map(action => ({ ref: action.payload.ref, ...action.payload.data()}))
);
}
getMsgs(topicId): Observable<CommentData[]>{
return this.afs.collection('/topics_msgs/' + topicId + "/comments").snapshotChanges().pipe(
mergeMap(actions => {
const commentsDataObservableArray: Observable<CommentData>[] = actions.map(a => {
const commentData = a.payload.doc.data();
return this.getUserData(commentData.user_id).pipe(
map(user => {
return {user: user.data(), ...commentData};
})
);
});
return combineLatest(commentsDataObservableArray);
})
);
}