Angular 2 guard - 对用户的异步请求

时间:2017-08-03 08:02:37

标签: angular authorization

异步http请求中返回值的问题。

如何等待订阅?

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ) {
    if (this.auth.currentUser) {
      return true;
    } else {
      this.auth.getUser()
        .subscribe(resp => {
          if (this.auth.currentUser) {
            return true;
          } else {
            this.router.navigate(['login'], {
              queryParams: {
                returnUrl: state.url
              }
            });
            return false;
          }
        })
    }
  }

刷新页面时没有返回任何结果,我将重定向到主页面。

1 个答案:

答案 0 :(得分:0)

你不会在'else'路径中返回任何内容:

canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
) {
  if (this.auth.currentUser) {
    return true;
  } else {
    // This path do not return any value !

    this.auth.getUser()
      .subscribe(resp => {
        if (this.auth.currentUser) {
          // This return is the return of your subscription callback function, not the canActivate one !
          return true;
        } else {
          this.router.navigate(['login'], {
            queryParams: {
              returnUrl: state.url
            }
          });
          // Same here
          return false;
        }
      })
  }
}

您需要在第二个路径中返回一个值(boolean,Promise或Observable):

canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
) {
  if (this.auth.currentUser) {
    return true;
  } else {
    return this.auth.getUser()
      .map(resp => {
        if (this.auth.currentUser) {
          // This return is the return of your subscription callback function, not the canActivate one !
          return true;
        } else {
          this.router.navigate(['login'], {
            queryParams: {
              returnUrl: state.url
            }
          });
          // Same here
          return false;
        }
      })
      .first();
  }
}

map与返回布尔值的回调一起使用,返回一个Observable。