Home > database >  angular Firestore: Observable.toPromise() versus Observalble.firstValueFrom();
angular Firestore: Observable.toPromise() versus Observalble.firstValueFrom();

Time:12-09

I am using Observables in an Angular project (13.0.3) in connection with the AngularFireStore database (angular/fire 7.2)

I need a simple method to just retrieve some data from a firestore collection and return it for use in a service. I don't need an observable, just the current value in the db.

So I wrote the following simple utilty method to just get a document and return it.:

async readDocument(collectionPath : string, key : string) : Promise<any> {
    let path = `${collectionPath}/${key}`
    let doc  = await this.firestore.doc(path).get().toPromise()
    return doc.data();         
  }

This actually works just fine and does what I want it to, except for observable.toPromise() appears as strike -hrough and is apparently depcreated and will be dropped in V8 of rxjs.

There is a message that appears in code complete suggest using methods firstValueFrom() or 'lastValueFrom() instead of .toPromise(), which makes sense, considering '.get() might return a collection of objects rather than a single object.

the problem is that even though the warning suggests it, Observable.lastValueFrom() doesn't actually exist as a method on the Observable. Trying to figure out why that is and what I can do to avoid using a deprecated method of rxjs Observable? I would really prefer to keep it simple and not have to subscribe and use pipes and all that just to fetch a single value from the db.

CodePudding user response:

it is not a method, but an utility function and this is how you should call it

import { firstValueFrom } from 'rxjs';
//...

const doc = await firstValueFrom(this.firestore.doc(path).get());
  • Related