简体   繁体   中英

Returning an Observable<boolean> from canActivate method and redirect on false

I have been searching for a solution with no luck. I need to call the server if a user is authorized and i need canActivate method to wait for the result for that call. But i can`t seem to put pieces together. Below is my code, my question is in the comments of the code.

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {

    let user: EUser = new EUser();
    user.sessionId = localStorage.getItem("sessionId");

    //I am not sure how to implement this part. 
    // I need to recieve the response and get user.isAuthorized value and return it
    // as an observable. 
    this.authenticationService.isAuthorized(user).subscribe((user)=>{
        //Here i need to get user.isAuthorized and 
        //if the value is false, i need to navigate to login with this.router.navigate['login'] and return it. 
        //if the values it true, i need the code continue as it is. 
    });

  }

AuthenticationService

isAuthorized(user:EUser){
    return this.http.post(ConnectionHelper.SERVER_URL+
          ConnectionHelper.USER+ConnectionHelper.ISAUTHORIZED,user).map(res => res.json());
}

Your approach is correct, you just need to map the server response to a bool value. For example:

export interface AuthState {
    username:string;
    sessionId:string;
    isAuthorized:boolean;
}

isAuthorized(user:EUser): Observable<AuthState> {
    return this.http.post(ConnectionHelper.SERVER_URL+
          ConnectionHelper.USER+ConnectionHelper.ISAUTHORIZED,user)
    .map(res => res.json());
}

// Inject Router instance in the constructor of the guard class
// import required rxjs operators
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    let user: EUser = new EUser();
    user.sessionId = localStorage.getItem("sessionId");
    return this.authenticationService.isAuthorized(user)
    .map(user => user.isAuthorized)
    .do(auth => {
      if(!auth){
         this.router.navigate(['/login']);
      }
    });
}

you can use promise and return value again for using in canActivate. if assume isAuthorized return boolean value you can use this code:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {

let user: EUser = new EUser();
user.sessionId = localStorage.getItem("sessionId");

return this.authenticationService.isAuthorized(user)
  .toPromise()
  .then((isValidUser) => {

    if (!isValidUser) {
      this.router.navigate['login'];
    }
    return isValidUser;
  });

}

note that then chain return Promise again and return isValidUser is accessible in next then call.

i use this pattern and it worked for me.

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