angular - 从 canActivate 方法返回 Observable<boolean> 并在 false 时重定向

标签 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. 
    });

  }

身份验证服务

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

最佳答案

您的方法是正确的,您只需将服务器响应映射到 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']);
      }
    });
}

关于angular - 从 canActivate 方法返回 Observable<boolean> 并在 false 时重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47155224/

相关文章:

css - 如何使用现有的 css 网格调整路由器模块的 Angular 组件

angular2 类型错误 : Cannot set property 'name' of undefined

javascript - 配置 Angular 2 HTTP 服务

html - 如何更改 md-tab-header 的颜色?

javascript - 错误 TS2339 : Property 'map' does not exist on type 'Observable<Response>'

angular - 在订阅回调函数中取消订阅?

Angular 2获取父激活路由

angular - 使用 Angular 2、jupyter 和 typescript 构建 docker 镜像

javascript - 如何在 RxJS 中设定的时间间隔后对整个流进行 forEach

angular - 类型 'paramMap' 上不存在属性 'ActivatedRoute' ./node_modules/@angular/router/index "' has no exported member ' ParamMap'