Search code examples
angulargoogle-cloud-firestorerxjsangularfire2

AngularFire read a Firestore document only once


Using Angular 17 and AngularFire 17, what is the best method for simply getting document data, just once, from a Firestore record?

I can get it with the following but this seems overkill as I assume I need to then immediately unsubscribe from the Observable?

const docRef = doc(this.fs, `projects/${id}`);
const projectData = docData(projectDocRef).subscribe(data=>{
   console.log(data)
})

I only want that initial snapshot and I definitely don't want to stay subscribed because the document will subsequently get updated on Firestore but those changes should not impact my app state.
I just want to grab the data once and then move on.

Not sure if its just me but the AngularFire docs are not very helpful. The Firestore docs have details of things like this...

let documentRef = firestore.doc('col/doc');

documentRef.get().then(documentSnapshot => {
  if (documentSnapshot.exists) {
    console.log('Document retrieved successfully.');
  }
});

But there doesn't seem to be an AngularFire equivalent?

Hopefully I'm missing something obvious - some RXJS thing maybe? :)


Solution

  • You could use take(1) to complete the observable!

    Take:

    Emit provided number of values before completing

    CODE:

    docData(projectDocRef).pipe(take(1)).subscribe(data=>{
       console.log(data)
    });