从canActivate方法返回Observable <boolean>并重定向为false

时间:2017-11-07 10:13:02

标签: angular rxjs angular-router angular-router-guards

我一直在寻找一个没有运气的解决方案。如果用户被授权我需要调用服务器,我需要canActivate方法来等待该调用的结果。但我似乎无法拼凑出来。下面是我的代码,我的问题是在代码的注释中。

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

2 个答案:

答案 0 :(得分:1)

您的方法是正确的,您只需要将服务器响应映射到bool值。例如:

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

答案 1 :(得分:0)

您可以再次使用promise并返回值,以便在canActivate中使用。 如果假设isAuthorized返回boolean值,则可以使用以下代码:

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

}

请注意,then链再次返回Promise,并且在下一个return isValidUser调用中可以访问then

我使用这种模式,对我有用。