在我的拦截器中,如果响应statusCode为401,我想在响应上添加管道并注销,但问题是当我放置catchError时,可观察的类型不是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);
}
}
}。
答案 0 :(得分:1)
抛出一个新错误,该错误将被转发,而不仅仅是返回错误:
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators'
...
catchError(er => {
if (er.status === 401) {
this.auth.logout();
}
return throwError(er);
})
答案 1 :(得分:1)
您可以通过以下方法处理Error
响应,请尝试
return next.handle(clonedRequest).do((event: HttpEvent<any>) => {}, (error: any) => {
if (error instanceof HttpErrorResponse) {
if (error.status == 401 || error.status == 403) {
this.auth.logout();
}
}
});
我希望这能解决您的问题:)
答案 2 :(得分:0)
这就是我的方法。
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// req = req.clone({headers: req.headers.set('source', 'WEB')});
req = req.clone({
headers: new HttpHeaders({
'source': 'WEB',
'Authorization': localStorage.getItem(TOKEN) || ''
})
});
return next.handle(req).pipe(map((e: HttpEvent<any>) => {
if (e instanceof HttpResponse) {
/* console.error(e);
console.log(e.status);*/
if (e.status === 401) {
throw new Error('invalid token');
}
}
return e;
}));
}
如果(如果是HttpResponse的instanceof)这个我,如果它的响应>> 如果它的响应然后按照您的喜好进行验证。此处我只是抛出错误,但是我们可以清除保存的令牌并重定向到登录页面