angular - Angular HttpClient 拦截器:刷新身份验证令牌
问题描述
这是我的拦截器代码
export class AuthInterceptorService implements HttpInterceptor {
constructor(private auth: AuthService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const userInfo = this.auth.getAuthToken();
const authReq = req.clone({ setHeaders: { Authorization: 'Bearer ' + userInfo.access_token, 'Content-Type': 'application/json' } });
return next.handle(authReq)
.pipe(catchError( err => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) { debugger;
console.log('this should print your error!', err.error);
}
}
}));
}
}
我收到以下错误
TS2345: Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<HttpEvent<any>>) => ObservableInput<{}>'. Type 'void' is not assignable to type 'ObservableInput<{}>'.
我想知道是否有解决此问题的方法?我想在 http 拦截器中实现刷新令牌功能。
解决方案
你能试试这个吗?
export class AuthInterceptorService implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
const userInfo = this.auth.getAuthToken();
const authReq = req.clone({
setHeaders: {
Authorization: "Bearer " + userInfo.access_token,
"Content-Type": "application/json"
}
});
// return next.handle(authReq)
// .pipe(catchError( err => {
// if (err instanceof HttpErrorResponse) {
// if (err.status === 401) { debugger;
// console.log('this should print your error!', err.error);
// }
// }
// }));
return next.handle(authReq).do(
(event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
},
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
console.log("this should print your error!", err.error);
}
}
}
);
}
}
推荐阅读
- matlab - 如何让matlab显示十进制数?
- c# - 在asp.net framework 4.0中,如何在没有nuget的情况下实现Stripe PaymentGateway?
- mysql - SQL 更新来自 select 的记录列表
- android - 如何在 RecyclerView 之间添加 Facebook Audience Network 原生广告
- python - 使用 Python 制作包含 100 多个绘图的 PDF 报告的最佳方法是什么?
- android - 在android中,如何在cardview左上角和右上角圆角设置imageview?
- javascript - 如果月份无效,如何从 DOB 计算年龄?
- javascript - 重试失败的 API 调用到 Angular 中的另一个源
- javascript - 使用纯 JS,我可以检查一个类是否正在使用中?
- css - 透明图像曲线轮廓(不是矩形边框)