1

我一直在寻找没有运气的解决方案。如果用户被授权,我需要调用服务器,并且我需要 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. 
    });

  }

身份验证服务

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

2 回答 2

3

您的方法是正确的,您只需要将服务器响应映射到一个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']);
      }
    });
}
于 2017-11-07T10:19:45.683 回答
-1

您可以再次使用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;
  });

}

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

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

于 2019-12-18T07:27:36.180 回答