Cloud Firestore 中 get() 和 onSnapshot() 的区别 [英] Difference between get() and onSnapshot() in Cloud Firestore

查看:21
本文介绍了Cloud Firestore 中 get() 和 onSnapshot() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 Firebase 的 Cloud Firestore 读取一些数据,但我已经看到了几种方法.我看到的示例使用了 get 和 onSnapshot 函数,如下所示:

I am reading some data from Firebase's Cloud Firestore but I've seen several ways to do it. The example I saw used the get and onSnapshot function like this:

db.collection("cities").doc("SF")
 .onSnapshot(doc => {
      console.log(doc.data());
 });

或者这个

var docRef = db.collection("cities").doc("SF");

docRef.get().then(doc => {
    if (doc.exists) {
         console.log("Document data:", doc.data());
    } else {
         console.log("No such document!");
    }
}).catch(function(error) {
   console.log("Error getting document:", error);
        });

它们之间有什么区别吗?

Is there any difference between them?

推荐答案

文档:

两种方法来检索存储在 Cloud Firestore 中的数据.任何一个这些方法中的一个可以用于文档、文档集合、或查询结果:

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries:

  • 调用一个方法来获取数据.
  • 设置侦听器以接收数据更改事件.

当您设置侦听器时,Cloud Firestore 会向您的侦听器发送一个数据的初始快照,然后每次创建另一个快照文档更改.

When you set a listener, Cloud Firestore sends your listener an initial snapshot of the data, and then another snapshot each time the document changes.

当您使用 get() 时,您检索单个文档的内容"只有一次.这是一种一劳永逸":如果(后端)Firestore 数据库中的文档发生更改,您将需要再次调用 get() 以查看更改.

When you use get() you "retrieve the content of a single document" only once. It's a kind of "get and forget": If the document changes in the (back-end) Firestore database you will need to call get() again to see the change.

相反,如果您使用 onSnapshot() 方法,您不断地听一个文档,如doc:

On the opposite, if you use the onSnapshot() method you constantly listen to a document as explained in the doc:

您可以使用 onSnapshot() 方法收听文档.首字母使用您提供的回调调用创建文档快照立即使用单个文档的当前内容.然后,每次内容改变,另一个调用更新文档快照.

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.

如这些文档中所述,这两种方法适用于一个文档或一组文档(包括 查询).

As explained in these docs, these two methods apply to one document or to a collection of documents (including a query).

这篇关于Cloud Firestore 中 get() 和 onSnapshot() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆