Sammy
Sammy

Reputation: 3687

Returning an Observable from a Promise that returns an Observable

I have the following function:

public isAuthenticated(): Observable < boolean > {
  return fromPromise(this.renewTokens()
    .then(() => {
      return this.fetchUserData().pipe(map(user => {
        // store the user object somewhere
        return user !== null;
      }));
    })
    .catch(error => {
      this.ctx.log.error('Token renewal error', error);
      return false;
    }));
}

Where I'm trying to renew the user token first (function renewTokens() that returns a Promise) then get the user profile using the fetchUserData() function which returns Observable<User>. I would like to store this user profile somewhere and then return an Observable<boolean> as shown.

Of course the above returns error TS2322: Type 'Promise<boolean | Observable<boolean>>' is not assignable to type 'Observable<boolean>'. which I totally understand but have no idea how to resolve.

Notice that I'm not trying to subscribe to fetchUserData() here yet, I'd like the caller of isAuthenticated() to do this. That would typically happen in Angular's CanActivate Router Guard.

Upvotes: 0

Views: 542

Answers (1)

martin
martin

Reputation: 96891

It seems like you just need to flatten the inner Observable (I didn't test this but I hope you'll get the point):

return fromPromise(this.renewTokens())
  .pipe(
    concatMap(() => this.fetchUserData()
      .pipe(
        map(user => {
          // store the user object somewhere
          return user !== null;
        })
      );
    ),
    catchError(error => {
      this.ctx.log.error('Token renewal error', error);
      return of(false);
    }),
  );

Upvotes: 1

Related Questions