简体   繁体   中英

Return Observable From Result Of Observable

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);
    }
  });
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM