1

UrlTree如果防护失败, 我正在尝试实现重定向用户。this.authService.isAuthenticated()返回可观察的。

以下不起作用,但它确实 console false

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree {
  this.authService.isAuthenticated().subscribe(isAuthenticated => {
    if (isAuthenticated) {
      return true;
    } else {
      console.log(isAuthenticated);
      return this.router.createUrlTree(['auth/sign-in']);
    }
  });
  return false;
}

但是,如果我删除订阅,则以下内容有效:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree {
  return this.router.createUrlTree(['auth/sign-in']);
}
4

3 回答 3

2

不知道您需要重定向用户。所以使用这个函数:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
   return this.authService.isAuthenticated().pipe(
             take(1),
             map(user => !!user), // Converting object to a boolean
             tap(loggedIn => {
                // If you not return any value
                // function will return loggedIn boolean value
                if (!loggedIn) {
                   this.router.navigate(['/login'])
                }
            })
      );
}
于 2019-07-23T15:10:15.667 回答
2

您不能从内部订阅返回(无论如何)。路由守卫可以返回布尔值或布尔值的可观察值。因此,在您的情况下,您需要返回一个可观察的布尔值。还值得一提的是,在您当前的代码中,由于这是异步的,因此无论登录状态如何,您当前返回的始终是,为什么? false获得经过身份验证的状态需要 x 时间,因此false每次都返回,angular 不等待响应,只是转到下一个可用代码,即return false;您当前代码中的代码。

因此,如前所述,返回一个可观察的,即使用map而不是subscribe

import { map, take } from 'rxjs/operators';

// ....

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  return this.authService.isAuthenticated()
    .pipe(
      take(1),
      map(isAuthenticated => {
        if (isAuthenticated) {
          return true;
        }
        // no need for else, if above is truthy, further code is not executed
        this.router.createUrlTree(['auth/sign-in']);
        return false;
      })
    );
}
于 2019-07-23T17:59:54.647 回答
0

@AJT82 答案在 Angular 8 中对我不起作用。返回 UrlTreeparseUrl并返回 atrue是它的唯一工作方式。

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.authService.auth$.pipe(
      map((authState: AuthState) => {
        console.log('=========root guard=============');
        if (!authState.isLoggedIn) {
          return this.router.parseUrl('/auth/login');
        }

        if (state.url === '' || state.url === '/') {
          if (authState.accessGroups.includes(AccessGroup.ADMIN)) {
            return this.router.parseUrl('/post/list');
          }
          if (authState.accessGroups.includes(AccessGroup.REEF)) {
            return this.router.parseUrl('/reef');
          }
        }
        return true;
      })
    );

而且我真的不明白为什么返回 UrlTree 是不够的。如果我不返回true路由器将被阻止。很奇怪。

设置 UrlTree 然后返回 True 也不起作用。只有返回UrlTree和返回true对我有用。

于 2019-12-02T06:27:26.097 回答