What is the difference between get() and valueChanges() in Angular Firestore query?
Solution 1
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.
Solution 2
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.
Related videos on Youtube
Daniel T.
Updated on December 05, 2020Comments
-
Daniel T. over 3 years
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?
-
Mayank Kataria about 2 yearsI don't think
get()
call will only retrieve data once. Its also an observable and it will trigger whenever a document data changes. Actual difference is thatvalueChanges()
can be used with@angular/fire
library whereasget()
call was initiated for plain vanilla js