问题
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?
回答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.
回答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.
来源:https://stackoverflow.com/questions/58154310/what-is-the-difference-between-get-and-valuechanges-in-angular-firestore-que