与.limitToLast进行分页时,如何仅使用.onSnapshot从Firebase获取新文档 [英] How do I only get new documents from firebase using .onSnapshot when used with .limitToLast for pagination
问题描述
我正在尝试使用Firebase无限滚动地实现聊天应用程序.问题是,如果在添加新消息时不清空消息数组,那么它们将被复制.如果我清空messages数组,那么它将不保留先前的消息.
I'm trying to implement a chat app with infinite scroll using Firebase. The problem is that if I don't empty my messages array when a new message is added then they're duplicated. If I empty the messages array then it doesn't keep the previous messages.
这是代码:
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 = [];
}
});
}
返回参考的聊天服务:
And the chat service that returns the reference:
getAllMessages(matchId: string): firebase.firestore.CollectionReference<firebase.firestore.DocumentData> {
return firebase
.firestore()
.collection(`matches`)
.doc(`${matchId}`)
.collection('messages');
}
我正在将来自集合的消息推送到message数组中.如果我不添加'this.messages = []',则每次将新消息添加到集合中时,它都会复制消息.
I'm pushing the messages from the collection in to a messages array. If I don't add 'this.messages = []' then it will duplicate messages every time a new one is added to the collection.
如何仅使用onSnapshot从Firebase获取新文档,而不是再次遍历所有集合?我只想要最后一条消息,因为我将使用另一个检索先前消息的查询来实现无限滚动.
How do I only get the new document from firebase with onSnapshot instead of it iterating through all of the collection again? I only want the last message because I'm going to implement infinite scroll with another query that retrieves previous messages.
任何帮助将不胜感激.
推荐答案
只要符合条件的新条目出现,查询将始终返回最后5个结果,这将创建重复项.您可以做的是监听快照之间的更改
the query will always return the last 5 result whenever a new entry that matches the condition occurs, which will create the duplicates. What you can do is to listen to changes between snapshots
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());
}
});
});
}
这篇关于与.limitToLast进行分页时,如何仅使用.onSnapshot从Firebase获取新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!