我有一个受登录保护的角度客户端应用程序。当我登录时,Web API 会返回 x 分钟后过期的访问令牌。 当访问令牌过期时,我想返回登录,但我不知道该怎么做。
这是我的
ErrorInterceptor
课程:
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
this.authenticationService.logout();
location.reload(true);
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
但是当令牌过期时,什么也不会发生。
有人可以给我一些建议吗?
使用HttpInterceptor:
https://angular.io/api/common/http/HttpInterceptor
在 Angular 中创建一个拦截器来检查 errStatus 401(未经授权)。
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private logoutService: LogoutService) { /* empty */ }
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).catch((err: HttpErrorResponse) => {
if (err && err.status) {
this.handleRequestErrors(err.status);
}
return Observable.throw(err);
});
}
/**
* handleRequestErrors
* @param err: The HTTP Error Code Status
*/
private handleRequestErrors(errStatus: number) {
switch (errStatus) {
case 401: { // Unauthorized
this.logoutService.removeStoredAuthentication();
break;
}
}
}
}