简体   繁体   English

有没有办法让 Firestore 实时监听器在客户端或服务器端持久化?

[英]Is there a way to make firestore real time listener persistent on client-side or server-side?

I'm new to firebase.我是火力基地的新手。 The goal is i want to only read all data in collection once and keep fetching new updates without refetching all data again when refreshing or closing the web app.目标是我只想读取一次集合中的所有数据,并在刷新或关闭 Web 应用程序时继续获取新更新,而无需再次重新获取所有数据。

Is it possible?是否可以? Probably not.可能不是。

db.collection("cities").where("state", "==", "CA")
.onSnapshot(function(snapshot) {
    snapshot.docChanges().forEach(function(change) {
        if (change.type === "added") {
            console.log("New city: ", change.doc.data());
        }
        if (change.type === "modified") {
            console.log("Modified city: ", change.doc.data());
        }
        if (change.type === "removed") {
            console.log("Removed city: ", change.doc.data());
        }
    });
});

There is no way to make a listener continue to work after the app or process that performs the query has been terminated.在执行查询的应用程序或进程终止后,无法使侦听器继续工作。

Consider instead adding a timestamp field to each document, and use that to filter for new documents past the last known timestampped document previously read.考虑为每个文档添加一个时间戳字段,并使用它来过滤之前读取的最后一个已知时间戳文档之后的新文档。

You can use snapshot.docChanges() to listen for changes.您可以使用 snapshot.docChanges() 来监听更改。 Like you have.就像你一样。

To maybe help, here is an example I did for a real-time chat app.为了可能有所帮助,以下是我为实时聊天应用程序所做的示例。 It's similar to your code.它类似于您的代码。 I put it inside the created hook.我把它放在创建的钩子里。

With this, I was able to load all data from a firestore doc and listen for newly added messages without having to reload the page.有了这个,我能够从 firestore 文档加载所有数据并监听新添加的消息,而无需重新加载页面。 When I added a new message it would appear without having to reload the page.当我添加一条新消息时,它会出现而无需重新加载页面。

created() {

    let ref = firestore.collection('< collection here >')
              .doc('< doc ID HERE >')
              .collection('< A Sub collection if you have one >')
              .orderBy('createdAt')

    ref.onSnapshot(snapshot => {

      snapshot.docChanges().forEach(change => {

        if(change.type == 'added') {
          let doc = change.doc

          this.messages.push({
            id: doc.id,
            name: doc.data().name,
            content: doc.data().content,
            timestamp: moment(doc.data().createdAt).format('lll'),
          })
        }
      });

    })
  },

In my data section, I had an empty array.在我的数据部分,我有一个空数组。 When the page loads everything in the doc is stored in the array, and when the doc changes, the change is pushed onto the array.当页面加载时,文档中的所有内容都存储在数组中,当文档更改时,更改会推送到数组中。 You can use this array with a v-for in your template and it will update when the doc changes.您可以在模板中将此数组与 v-for 一起使用,它会在文档更改时更新。

messages: [],

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

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