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

查看:197
本文介绍了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()方法,则您将不断地收听文档,如

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天全站免登陆