当与.limitToLast一起用于分页时,如何仅使用.onSnapshot从firebase获取新文档



我正在尝试使用Firebase实现一个具有无限滚动功能的聊天应用程序。问题是,如果在添加新消息时不清空消息数组,那么它们就会重复。如果清空消息数组,则它不会保留以前的消息。

这是代码:

getAllMessages(matchId: string) {
this.chatSvc.getAllMessages(matchId)
.orderBy('createdAt', 'asc')
.limitToLast(5)
.onSnapshot((doc) => {
if (!doc.empty) {
this.messages = [];
doc.forEach((snap) => {
this.messages.push({
content: snap.data().content,
createdAt: snap.data().createdAt,
sendingUserId: snap.data().sendingUserId,
receivingUserId: snap.data().receivingUserId
});
});
} else {
this.messages = [];
}
});
}
以及返回引用的聊天服务:

getAllMessages(matchId: string): firebase.firestore.CollectionReference<firebase.firestore.DocumentData> {
return firebase
.firestore()
.collection(`matches`)
.doc(`${matchId}`)
.collection('messages');
}

我正在将集合中的消息推送到消息数组中。如果我不添加"this.messages=[]",那么每次向集合中添加新消息时,它都会重复消息。

如何使用onSnapshot仅从firebase获取新文档,而不是再次迭代所有集合?我只想要最后一条消息,因为我将用另一个检索以前消息的查询实现无限滚动。

如有任何帮助,我们将不胜感激。

每当出现与条件匹配的新条目时,查询将始终返回最后5个结果,这将创建重复项。您可以做的是倾听快照之间的变化

getAllMessages(matchId: string) {
this.chatSvc.getAllMessages(matchId)
.orderBy('createdAt', 'asc')
.limitToLast(5)
.onSnapshot((snapshot) => {
snapshot.docChanges().forEach((change) => {
// push only new documents that were added
if(change.type === 'added'){
this.messages.push(change.doc.data());
}
});
});
}

最新更新