Categories
Angular RXJS

Angular RXJS Observables – toPromise on an observable not working

If you are trying to change an observable to a promise, the promise won’t fire until the observable completes.

What this means for an Angular developer, especially one using Firebase and AngularFire, is that if you are writing a method like this:

public authState(): Observable<User> {
  return this.afAuth.authState;
}

And you are trying to get it to work in async code and return a promise:

public async doSomethingWithAuthUser() {
  const user = await this.authState().toPromise()
  // do the next thing...
}

The code will get hung up, because the observable doesn’t complete.

However, if you change it so that the observable only returns one value:

public async doSomethingWithAuthUser() {
  const user = await this.authState().pipe(
    take(1)
  ).toPromise()
  // do the next thing...
}

Now the observable completes, and your code will continue to run.

Using SnapshotChanges with toPromise()

Another gotcha is trying to use toPromise on a query that uses snapshotChanges to get the data.

SnapshotChanges doesn’t complete as well, so we either have to write it with a take(1) like we did with the authState or, you can use .get() on the query instead.

If you are trying to use promises, just remember that they won’t give you the “Realtime” feature that from Firestore. That only happens if you are subscribing to a stream with either snapshotChanges() or valueChanges().

Leave a Reply

Your email address will not be published. Required fields are marked *