0

I am very new to RxJS, so I'm not quite sure what question I should be asking here. I have a service that returns an Observable boolean:

@Injectable
export class UserService {
  private isLoggedInSubject = new ReplaySubject<boolean>(1);
  public isLoggedIn = this.isLoggedInSubject.asObservable();
}

In an Angular 6 route guard I passing on that value to prevent access to a route:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  return this.userService.isLoggedIn.pipe(take(1)); 
}

How can I take this value, and return an Observable based on the result? I have tried multiple variations of something like this, but seem to be missing some fundamental concept as this has to be a fairly common thing.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  const isLoggedIn = this.userService.isLoggedIn.pipe(take(1));

  return isLoggedIn.[???something????](x => {
    if (x) {
      console.log('is logged in');
      return Observable.of(true);
    } else {
      console.log('is not logged in ');
      return Observable.of(false);
    }
  });
}

1 Answer 1

1

You just chain it with more operators:

return this.userService.isLoggedIn.pipe(
  take(1),
  concatMap(x => {
    if (x) {
      console.log('is logged in');
      return Observable.of(true);
    } else {
      console.log('is not logged in ');
      return Observable.of(false);
    })
  },
);

Btw, you don't even need to be returning Observable.of. You can use just map and return eg. false.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.