【问题标题】:Angular4 issue with http requestshttp请求的Angular4问题
【发布时间】:2018-01-25 07:59:01
【问题描述】:

在我的 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 函数中,我无法获得该函数的确切输出值。 Bellow 是我的 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()); 时,它会打印订阅者对象而不是返回值。如何从 isLogedIn() 函数返回值?

【问题讨论】:

    标签: javascript angular callback return-value angular4-router


    【解决方案1】:

    因为您确实返回了订阅。 `

    • this.http.get(...)Observable
    • this.http.get(...).map(...)Observable
    • this.http.get(...).map(...).subscribe(...)Subscription

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

    我对你的建议是什么:在警卫中返回 observable 本身(canActivate 接受 Observable<boolean> 作为返回)。不要打电话给subscribeisLogedIn()

    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:最后一个是操纵您的响应以返回一个布尔值。最后,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,这是一个独立的回调,来管理你的路由。

    【讨论】:

      【解决方案2】:

      你的功能应该是这样的

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-12
        • 2015-09-13
        • 1970-01-01
        • 1970-01-01
        • 2017-04-22
        • 2011-03-20
        • 2015-06-13
        相关资源
        最近更新 更多