简体   繁体   English

返回一个 Observable<boolean> 来自 canActivate 方法并重定向到 false

[英]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.如果用户获得授权,我需要调用服务器,并且我需要 canActivate 方法来等待该调用的结果。 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.您的方法是正确的,您只需要将服务器响应映射到bool值。 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.您可以再次使用 promise 和 return value 以在 canActivate 中使用。 if assume isAuthorized return boolean value you can use this code:如果假设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;
  });

} }

note that then chain return Promise again and return isValidUser is accessible in next then call.请注意, then链再次返回Promise并在 next then调用中可以访问return isValidUser

i use this pattern and it worked for me.我使用这种模式,它对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 返回一个 Observable<boolean> 来自 canActivate 并重定向为 false</boolean> - Returning an Observable<boolean> from canActivate and redirect on false CanActivate Observable 在服务检查延迟时返回 false - CanActivate Observable returning false when delay in service check 角卫队canActivate方法不适用于Observable <boolean> - Angular guard canActivate method dont work with Observable<boolean> CanActivate:使用套接字侦听器的可观察布尔值 - CanActivate: Observable Boolean with Socket listener 处理来自 Observable 的 HttpErrorResponse,该 Observable 在 canActivate() 中不返回布尔值 - Handle HttpErrorResponse from an Observable that doesn't return a boolean inside a canActivate() Angular - 从 CanActivate 中的 Observable 服务获取布​​尔值 - Angular - Get Boolean Value from a Observable Service inside the CanActivate 为什么 Angular Guards canActivate 方法总是返回 false? - Why Angular Guards canActivate method is always returning false? 在从 authGuard 的 canActivate 接收到 false 时进行路由器重定向 - Making router redirect upon receiving false from authGuard's canActivate 路由器:从`canActivate`方法返回的promise中重定向 - Router: Redirect from within a promise returned by a `canActivate` method 如何返回 Observable<boolean> 在 Angular 6 中的受保护路线上的 canActivate - How to return Observable<boolean> in canActivate on a guarded route in Angular 6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM