angular - 如果有 401 响应,角度拦截器会注销应用程序吗?
问题描述
在我的拦截器中,如果响应 statusCode 为 401,我想在响应上放置一个管道并注销,但问题是当我放置一个 catchError 时,observable 不是 HttpEvent 类型并且拦截函数期望返回该类型?
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = `Agency ${this.auth.token}`;
const requestWithHeaders = req.clone({ setHeaders: {'Content-Type': 'application/json'}});
if (!!this.auth.token) {
const authReq = requestWithHeaders.clone({ setHeaders: { Authorization: authToken} });
return next.handle(authReq).pipe(
catchError(er => {
if (er.status === 401) {
this.auth.logout();
}
return er;
})
);
} else {
return next.handle(requestWithHeaders);
}
}
}。
解决方案
抛出一个新的错误,它将被转发而不是仅仅返回错误:
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators'
...
catchError(er => {
if (er.status === 401) {
this.auth.logout();
}
return throwError(er);
})
推荐阅读
- ios - 自动使用 TouchID 进行身份验证,不显示任何提示
- python - 在 Python 中使用正交多项式平滑大型噪声数据集
- c# - Azure 存储“租约” - 正确的异常方法
- java - java.lang.UnsatisfiedLinkError:java.library.path 中没有 netty-transport-native-epoll
- javascript - Fullcalendar Unknown option 'header' 版本 5.5.1
- python - matplotlib.pyplot 中的 HSV 颜色图
- c++ - 某些程序的 CreateProcessA 失败
- c# - GraphQL nuGet v4 DateTimeGraphType
- reactjs - 在一个组件中使用多个草稿 js 编辑器
- python-3.8 - 问题 Seq 文件 < ComObject Maxim.CCD CAMERA “序列的目标路径似乎不是有效文件夹” > Python 3.8