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?
snapshotChanges() Metadata provides you the underyling DocumentReference , document id, and array index of the single document. Having the document's id around makes it easier to use data manipulation methods.
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: Call a method to get the data. Set a listener to receive data-change events.
Firestore addSnapshotListener is querying all data when a new document added - Android.
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.
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!
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
})
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.
valueChanges()
is used in the library angularfire2. According to the docs:
Returns an Observable of document data. All Snapshot metadata is stripped. This method provides only the data.
If you are doing an angular project, then you can use the library angularfire2
which contains the method valueChanges()
get()
is also used to retrieve the contents of a single document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With