CanActivate不激活路由

时间:2019-07-02 13:46:02

标签: angular ngrx angular-guards

检测到登录的用户时,我正在尝试将用户重定向到应用程序或登录屏幕。

我正在使用Angular“〜8.1.0-next.2”。第一次尝试在应用程序上使用Guards。

// IsLoggedGuard 
canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

  console.log(state.url);

  return this.checkStore().pipe(
    switchMap(() => of(true)),
    catchError(() => of(false))
  )
}

checkStore(): Observable<boolean> {
  return this.store.select(selectAuthIsLogged).pipe(
    tap( isLogged => {
      if ( !isLogged ) 
        this.store.dispatch(AuthActions.Load_Current_User())
    }),
    filter(isLogged => isLogged),
    take(1)
  )
}
// LoginGuard
canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

  return this.store.select(selectAuthIsLogged)
  .pipe(
    tap( logged => {
      if ( logged ) 
        this.router.navigate(['']);

      return of(!logged);
    })
  )
}
// AuthGuard
canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

  return this.store.select(selectAuthIsLogged)
    .pipe(
      tap( logged => {
        if ( !logged ) 
          this.router.navigate(['login']);

        return of(logged);
      })
    )
}

我有两条路线['login',''],每条路线都叫两个警卫: “登录”:IsLoggedGuard和LoginGuard ”:IsLoggedGuard和AuthGuard

在AuthGuard上,如果记录为true,则调用应用程序。但是我从来没有访问过带有CanActivate定义的登录名。如果我删除CanActivate,则可以访问登录屏幕。

1 个答案:

答案 0 :(得分:0)

您必须在警惕中返回true或false,因为路由器期望这样的布尔返回值

@Injectable()
export class AuthGuardService implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  async canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> {
    const user = await this.authService.isAuthenticated();

    if (!user) {
      this.router.navigateByUrl("/account");
      return false;
    }

    return true;
  }
}

所以您的代码应该是

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

  return this.store.select(selectAuthIsLogged)
    .pipe(
      tap( logged => {
        if ( !logged ) {
          this.router.navigate(['login']);
          return false
        } 

        return true;
      })
    )
}