简体   繁体   中英

Angular - Get Boolean Value from a Observable Service inside the CanActivate

I'm trying to get the boolean value and return it inside the CanActivate in angular.

Here's my sample service:

isActiveUser<bool>(){
    return this.http.get<boolean>(apiGetUserStatus);
}

Here's my canActivateMethod

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshow): Observable<boolean> | Promise<boolean> | boolean){
    var status = this.myService.isActiveUser().subscribe((active: boolean)=>{
        return active;
    })

    return status;
}

Unfortunately, when I'm trying to console log the status it shows the observable stuff, not the actual boolean value. Any help regarding this?

canActivate can also return an observable. So just change your code this way.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        const subject = new Subject<boolean>();
        this.myService.isActiveUser().subscribe((result) => {
            subject.next(result);
        });
        return subject;
    }

Try to just return the isActiveUser() function.

canActivate(
  route: ActivatedRouteSnapshot, 
  state: RouterStateSnapshow
): Observable<boolean> {
  return this.myService.isActiveUser();
}

Update: additional logic from isActiveUser()

You could use RxJS operators like map or tap to either transform the data or perform some-effects from the result of isActiveUser() .

canActivate(
  route: ActivatedRouteSnapshot, 
  state: RouterStateSnapshow
): Observable<boolean> {
  return this.myService.isActiveUser().pipe(
    map((activeUser: boolean) => {
      // do something
      return isUserAdmin();   // <-- eg.: function that returns boolean
    }),
    tap((user: boolean) => {
      // do some side-effects
      // tap doesn't have to return anything
    }),
    switchMap((user: boolean) => {
      // you could also map to another observable using `switchMap`
      return someFunc(); // <-- eg: function returns an `Observable<boolean>`
    })
  );
}

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