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

当与.limitToLast一起用于分页时,如何仅使用.onSnapshot从firebase获取新文档,firebase,pagination,infinite-scroll,Firebase,Pagination,Infinite Scroll,我正在尝试使用Firebase实现一个带有无限滚动的聊天应用程序。问题是,如果在添加新消息时不清空消息数组,那么它们就会被复制。如果我清空messages数组,那么它不会保留以前的消息 代码如下: getAllMessages(matchId:string){ this.chatSvc.getAllMessages(matchId) .orderBy('createdAt','asc') .limitToLast(5) .onSnapshot((文档)=>{ 如果(!单据为空){ this.m

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

代码如下:

getAllMessages(matchId:string){
this.chatSvc.getAllMessages(matchId)
.orderBy('createdAt','asc')
.limitToLast(5)
.onSnapshot((文档)=>{
如果(!单据为空){
this.messages=[];
文件格式((快照)=>{
这个是.messages.push({
内容:snap.data().content,
createdAt:snap.data().createdAt,
sendingUserId:snap.data().sendingUserId,
receivingUserId:snap.data().receivingUserId
});
});
}否则{
this.messages=[];
}
});

}
每当出现与条件匹配的新条目时,查询将始终返回最后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());
          }
        });
      });
  }