【发布时间】:2018-09-25 10:32:48
【问题描述】:
我有基本的后卫。用户在登录时被重定向。
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);
我在使用管道传递 next.handle() 时做错了什么?
【问题讨论】: