简体   繁体   English

如何从Firebase Firestore获取带有change.type ==“ added'的实时文档更新

[英]How do I get Realtime document updates from Firebase Firestore with change.type =="added'

I presently can realtime update modified data with the following code. 我目前可以使用以下代码实时更新修改后的数据。 What I am trying to accomplish is to listen for new documents added and then realtime update my posts. 我要完成的工作是听添加的新文档,然后实时更新我的​​帖子。 I believe it is in line 8 // listen for new docs that is causing the issues. 我相信它是在第8行中// //引起问题的新文档。

getPosts() {
  this.posts = [];

  let loading = this.loadingCtrl.create({
    content: "Loading Feed..."
  });

  loading.present();

  let query = firebase.firestore().collection("posts").orderBy("created", "desc").limit(this.pageSize);

  query.onSnapshot((snapshot) => {
    let changedDocs = snapshot.docChanges();

    changedDocs.forEach((change) => {

      if (change.type == "added") {
        console.log("New Message: ", change.doc.data());
        for (let i = 0; i < this.posts.length; i++) {
          // if (this.posts[i].id === change.doc.id) {
          if (change.doc.isEqual(this.posts[i])) {
            this.posts[i] = change.doc;
          }
        }
      }


      if (change.type == "modified") {
        console.log("Modified Message: ", change.doc.data());
        for (let i = 0; i < this.posts.length; i++) {
          if (this.posts[i].id == change.doc.id) {
            this.posts[i] = change.doc;
          }
        }
      }

    })
  })

query.get()
  .then((docs) => {

    docs.forEach((doc) => {
      this.posts.push(doc);
    })

    loading.dismiss();

    this.cursor = this.posts[this.posts.length - 1];

    console.log(this.posts);

  }).catch((err) => {
    console.log(err)
  })
}

It looks to me like the problem is that you're checking to see if this.posts[i] equals the added doc, and by definition, your doc won't be included in this.posts , since it's a new document. 在我看来,问题在于您正在检查this.posts[i]等于添加的文档,并且根据定义,您的文档不会包含在this.posts ,因为它是一个新文档。 There's nothing in the code that's updated this.posts with the new data yet. 代码中没有任何东西this.posts使用新数据更新this.posts

That said, based on your code, I'm not sure I would even bother looking at docChanges. 就是说,根据您的代码,我不确定我是否还要去看docChanges。 The point of using docChanges is when you want to do something very specific when a doc changes, like adding a fade-out animation when a document is removed from your data or something. 使用docChanges的目的是当您想在文档更改时做一些非常特定的事情,例如在从数据或其他内容中删除文档时添加淡出动画。 Can you simply blow away your old posts array and set the new array equal to the documents you get back in your snapshot listener? 您可以简单地删除旧的帖子数组,并将新数组设置为等于您在快照侦听器中返回的文档吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM