我跟着几篇文章在Angular上实现JWT身份验证,似乎一切正常,除了检测401未经授权。
我想将用户重定向到登录页面,但我无法检测到401错误。
我有这堂课:
export class JwtInterceptor implements HttpInterceptor {
constructor(public authService: AuthService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log('HTPP REQUEST');
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
this.authService.collectFailedRequest(request);
console.log('Login boy');
}
}
});
}
}
但不确定在哪里使用它。我的auth.service.ts
包含login()
和getToken()
方法,jwt.interceptor.ts
包含
答案 0 :(得分:0)
providers: [PagerService, AuthService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}, {
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
}
]
I have to add multiple interceptors in the module.app.ts
. Don't forget to add @Injectable()
before export class...
in the interceptor.