http请求的Angular4问题

Angular4 issue with http requests

在我的 Angular 4 应用程序中,我正在开发一个 oath guard 服务。在那里我想检查令牌是否有效,如果没有,用户需要重新登录。

以下是我用来实现我想要的功能的函数:

isLogedIn(){

    return this.http.get(this.baseUrl+"/check-token?token="+this.currentUser.token).map(res => res.json())
    .subscribe(response => {
          let logedinUser = JSON.parse(localStorage.getItem('currentUser'));
                if(response.message == "_successful" && localStorage.getItem("currentUser") != null){
                    return true;
                }else{
                    return false;
                }
             },err =>{ 
                console.log(err); 
                return false;
           });

}

但问题在 auth gurd 函数中,我无法获得此函数的确切输出值。波纹管是我的 auth gurd 函数:

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    console.log(this.userService.isLogedIn());
    if (this.userService.isLogedIn()) {
      return true;
    } else {
      this.router.navigate(['/login'], {
        queryParams: {
          return: state.url // curent url as a parameter to the login page
        }
      });
      return false;
    }
  }

当我使用 console.log(this.userService.isLogedIn()); 时,它打印订阅者对象而不是 return 值。我如何 return isLogedIn() 函数的值?

你的函数应该是这样的

isLogedIn(): Observable<boolean> {
    return this.http.get(this.baseUrl + '/check-token?token=' + this.currentUser.token)
        .map((res: Response) => {
            const response = res.json();
            return response.message == "_successful" && localStorage.getItem("currentUser") != null;
        }).catch((error: Response) => {
            return false;
        });
}

因为您return确实在订阅。 `

  • this.http.get(...) 是一个 Observable;
  • this.http.get(...).map(...) 是一个 Observable;
  • this.http.get(...).map(...).subscribe(...) 是一个 Subscription;

subscribe 方法 return 是 Subscription,而不是 subscribe 例程中的 return something

我建议你什么:return 守卫中的 observable 本身(canActivate 接受 Observable<boolean> 作为 return)。不要在 isLogedIn() 呼叫 subscribe

isLogedIn(): Observable<boolean>{

return this.http.get(this.baseUrl+"/check-token?token="+this.currentUser.token).map(res => res.json())
.map(response => {
      let logedinUser = JSON.parse(localStorage.getItem('currentUser'));
            if(response.message == "_successful" && localStorage.getItem("currentUser") != null){
                return true;
            }else{
                return false;
            }
         });
}

请注意,我两次调用 map:最后一次是操纵您对 return 布尔值的响应。最后,在 canActivate:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

  return this.userService.isLogedIn().do(response => {
    if (!response) {
      this.router.navigate(['/login'], {
        queryParams: {
          return: state.url // curent url as a parameter to the login page
        }
      });
    }
  })
}

我插入运算符 do,这是一个独立的回调,用于管理您的路由。