Angular Firebase-如何获取收集时每个文档的附加数据
我尝试获取每个消息文档的用户。我们有:Angular Firebase-如何获取收集时每个文档的附加数据,angular,firebase,google-cloud-firestore,observable,angularfire2,Angular,Firebase,Google Cloud Firestore,Observable,Angularfire2,我尝试获取每个消息文档的用户。我们有: users user_id => user_data message msg_id => { message, user_id } 所以我试着基于: } 在组件中: this.firebaseService.getMsgs(this.id).subscribe( msgs => { console.log(msgs); this.messages = msgs; }) 但它当然不能工作——内部映射不会返回承诺之
users
user_id => user_data
message
msg_id => { message, user_id }
所以我试着基于:
}
在组件中:
this.firebaseService.getMsgs(this.id).subscribe( msgs => {
console.log(msgs);
this.messages = msgs;
})
但它当然不能工作——内部映射不会返回承诺之外的任何内容,因此组件会收到一个未定义的列表
关于如何处理这件事,我有点被困在这里了。非常感谢。使用高阶观测值将数据转换为适合您需要的类型。关于你的问题,根据我的理解,你可以这样做:
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);
})
);
}
谢谢,我最终使用了一个类似的解决方案,但我承诺,我会尝试你的解决方案,因为它看起来不错。
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);
})
);
}