【问题标题】:How do I only get new documents from firebase using .onSnapshot when used with .limitToLast for pagination与 .limitToLast 一起用于分页时,如何仅使用 .onSnapshot 从 firebase 获取新文档
【发布时间】:2020-08-17 13:36:11
【问题描述】:

我正在尝试使用 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 获取新文档,而不是再次遍历所有集合?我只想要最后一条消息,因为我将使用另一个检索先前消息的查询来实现无限滚动。

任何帮助将不胜感激。

【问题讨论】:

    标签: firebase pagination infinite-scroll


    【解决方案1】:

    只要出现与条件匹配的新条目,查询将始终返回最后 5 个结果,这将创建重复项。你可以做的是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());
              }
            });
          });
      }
    
    

    【讨论】:

      猜你喜欢
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2019-01-15
      • 2020-11-02
      • 1970-01-01
      • 2021-06-03
      • 2020-11-01
      相关资源
      最近更新 更多