Angular Firestore 查询中的 get() 和 valueChanges() 有什么区别? [英] What is the difference between get() and valueChanges() in Angular Firestore query?

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

问题描述

正如标题所说,我想问一下在 Angular Firestore 中执行查询时 get() 和 valueChanges() 之间有什么区别(如果有的话).

As the title says I would like to ask what is the difference (if there is any) between get() and valueChanges() when performing a query in Angular Firestore.

在读取/成本方面,两者之间是否也有任何优点/缺点?

Are there also any advantages/disadvantages between the two maybe regarding the reads/costs?

推荐答案

valueChangesget() 的主要区别在于,get(),您只获得数据一次,而 valueChanges(和 snapshotChanges)会在链接到的数据库中发生变化时自动触发您正在收听的文件/收藏.

The main difference between valueChanges and get(), is that with get(), you get the data only once, whereas valueChanges (and snapshotChanges) is automatically fired whenever something changes in the database linked to that document/collection that you are listening to.

后者是 firebase 实时数据库的美妙之处,因为您不需要轮询或其他任何方式来获取最新数据,firebase 会处理所有这些!

The latter is the beauty of firebase realtime database, since you don't need to poll or anything else to get the latest data, firebase takes care of all of that!

在我看来 get() 很有用,例如,当您更新集合中的文档,然后在更新后立即想要对该文档执行某些操作,并且只获取一次时,比如:

In my opinion get() is useful to use when you for example update a document in a collection, and then instantly want to do something with that document after the update, and only fetch that once, like:

const docRef= this.afs.collection(colId).doc(docId).set(...)

docRef.get().pipe(
  map(doc => doc.data())
)
.subscribe(data => {
   // do stuff with document
})

当然,您可以使用例如 valueChanges 调用文档并附加一个 pipe(take(1)),但是 get()在这种情况下非常方便.

Of course you could call the document with for example valueChanges and attach a pipe(take(1)), but get() is pretty handy in this case.

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

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