Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between get() and valueChanges() in Angular Firestore query? [closed]

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?

like image 385
Daniel T. Avatar asked Sep 29 '19 10:09

Daniel T.


People also ask

What is snapshotChanges?

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.

How do I get data from firestore snapshot?

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.

What is addSnapshotListener?

Firestore addSnapshotListener is querying all data when a new document added - Android.


2 Answers

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.

like image 154
AT82 Avatar answered Oct 19 '22 11:10

AT82


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.

like image 39
Peter Haddad Avatar answered Oct 19 '22 10:10

Peter Haddad