使用异步方法验证时,是否可以从 Angular 中的 Guard 中重定向?

Is there a way to redirect if from within Guard in Angular when using asynchronous method to validate?

在我的 Angular(6.x.x) 项目中,我在某些路由上实施了一个 Guard,如果失败,它应该重定向到“/login”。 Guard 依赖于 AuthService 中的异步方法来验证用户。

// AuthService
checkLogin(): Observable<boolean> {
  return this.http
    .get<boolean>(`${this.apiUrl}/users/autologin`)
    .pipe(
      map(result => result === true),
      catchError(error => of(false))
    );
}

// AuthGuard
canActivate(next: ActivatedRouteSnapshot, 
  state: RouterStateSnapshot): Observable<boolean> {
    return this.authService.checkLogin();
}

如何实现?

注意:如果canActivate里面的代码是同步的,我知道怎么做。

代码示例:https://stackblitz.com/edit/angular-async-guard-redirect?file=src%2Fapp%2Fapp.module.ts

你可以在 AuthGuard 的 Observable pipe 中添加一个 tap,像这样:

return this.authService.checkAuthentication().pipe(
  tap(authenticated => {
    if (!authenticated) {
      // Add your redirect in here
    }
  })
);

这样,您可以在 return 之前对 Observable 的值做出反应。

您可以像这样更改 authservice。

   // AuthService
checkLogin(): Observable<boolean> {
  return this.http
    .get<boolean>(`${this.apiUrl}/users/autologin`)
    .pipe(
      map(result => { if(result === true)
                        {
                            returrn true;
                        }
                        this.router.navigateByUrl('/login');
                        return false;
                        }),
      catchError(error => of(false))
    );
}