我有基本的后卫。用户登录后将被重定向。
export class AuthGuard implements CanActivate {
constructor(private router: Router, private auth: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.auth.isAuthenticated().pipe(
map(isAuthenticated => {
if (isAuthenticated) {
this.router.navigate(environment.redirectPage);
return false;
}
return true;
})
);
}
}
这些是用于检查身份验证的功能
verifyToken (token: string): Observable<any> {
const data = {'token': token};
return this.http.post(`${this.url}/jwt/verify/`, data);
}
isAuthenticated () {
const token = localStorage.getItem('token');
if (token) {
return this.verifyToken(token).pipe(
map(data => true),
catchError (error => {
localStorage.removeItem('token');
return of(false);
}),
shareReplay()
);
}
return of(false);
}
我有自定义拦截器
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('token');
if (token) {
request = request.clone({setHeaders: {
Authorization: `JWT ${token}`
}});
}
return next.handle(request).pipe(catchError((error, caught) => {
if (error.status === 401) {
this.router.navigate([`/auth`]);
}
return of(error);
}) as any);
}
此错误是在将管道添加到handle()后发生的
所以这会导致错误:
return next.handle(request).pipe(catchError((error, caught) => {
if (error.status === 401) {
this.router.navigate([`/auth`]);
}
return of(error);
}) as any);
但不是:
return next.handle(request);
我用pipe'ing next.handle()做错什么了?
答案 0 :(得分:1)
您必须在next.handler
中重新抛出错误,以使您的AuthGuard
能够捕获该错误。
return next.handle(req).pipe(
catchError(err => {
return throwError(err);
})
);
然后,您可以针对防护中的错误进行任何操作:
return this.auth.isAuthenticated().pipe(
map(isAuthenticated => {
if (isAuthenticated) {
this.router.navigate(environment.redirectPage);
return false;
}
return true;
}),
catchError(err => {
this.router.navigate(['/sign-in']);
return of(err);
})
);