0

在我的 Angular(6.xx) 项目中,我在某些路由上实现了一个 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

4

2 回答 2

1

您可以在 AuthGuardtap的 Observable中添加一个,如下所示:pipe

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

这样,您可以Observable在返回 ' 值之前对其做出反应。

于 2018-09-26T05:03:20.157 回答
0

您可以像这样更改 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))
    );
}
于 2018-09-26T05:06:14.020 回答