angulartypescriptpromiserxjsangular-promise

Subscription to promise


In my Angular 7 application I have next function:

  getUserData(uid) {
    return this.fireStore.collection('users').doc(uid).valueChanges().subscribe(data => {
      this.writeCookie(data)
      this.currentUser = data;
    })
  }

And I want to use this function inside another method:

   someMethod() {
      ...
      new Promise(this.getUserData(uid))
         .then(() => {...})
      ...
   }

But I can't do this, because TypeScript throw an error:

Argument of type 'Subscription' is not assignable to parameter of type '(resolve: (value?: {} | PromiseLike<{}>) => void, reject: (reason?: any) => void) => void'. Type 'Subscription' provides no match for the signature '(resolve: (value?: {} | PromiseLike<{}>) => void, reject: (reason?: any) => void): void'.ts(2345)

How can I transform getUserData() method to a promise, or use forJoin instead?

Thanks in advance.


Solution

  • subscribe changes the type from Observable to Subscription, thus causing the type error.

    What you probably want is to convert your Observable to a Promise, while preserving the function call. You can do this, by piping the Observable through tap and then converting the result with toPromise. Like this:

    getUserData(uid) {
      return this.fireStore.collection('users').doc(uid).valueChanges().pipe(
        tap(data => {
          this.writeCookie(data)
          this.currentUser = data;
        }),
        first()
      ).toPromise()
    }
    

    Make sure to create a completing pipe, like you can do with the first operator, otherwise the Promise will never resolve.

    You can leave out new Promise(...) in your consumer.