如何使用angular

时间:2018-10-20 05:58:53

标签: angular angular-httpclient

我可以保护我的主页,如下所示。 checkTokenValidation是我从服务器检查令牌验证的一种方法。当服务器响应为false时,我的代码似乎停止了,并且map中的所有内容都不再起作用。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    return this.authService.checkTokenValidation().pipe(
      map((data) => {
          if (data['ok']) {
            this.router.navigate(['/overview']);
            return false;
          } else {
            return true;
          }
        },
        (error: string) => {
          console.log(error);
        })
    );
  }

这是我的checkTokenValidation代码:

 checkTokenValidation() {
 const token = this.getToken();
    return this.httpClient.get('http://185.69.54.21/back_end/web/site/check-token', {
      headers: new HttpHeaders().append('Authorization', `Bearer ${token}`)
    });
  }

1 个答案:

答案 0 :(得分:0)

问题

可疑的问题是-

  1. 在Guard中导航。因此最好从那里删除。

  2. 我猜条件是错误的。如果数据正常,则应返回true,否则返回false;

  3. 如果发生错误,则返回false;

修改后的代码

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    return this.authService.checkTokenValidation().pipe(
      map((data) => {
          if (data['ok']) {
            //this.router.navigate(['/overview']); //<-- remove this.
            return true; //<- return true if response is ok
          } else {
            return false;  //<- return false if response is not ok
          }
        },
        (error: string) => {
          console.log(error);
          return false;   //<- return false in case of error
        })
    );
  }