我有一个用于HttpInterceptor的以下代码,但是我无法使它的响应拦截器部分起作用:
import { Injectable } from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserService } from './user.service';
import { tap, map } from 'rxjs/operators';
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
constructor(private user: UserService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (!localStorage.getItem('token')) {
const modified = req.clone();
return next.handle(modified)
.pipe(
tap(event => {
if (event instanceof HttpErrorResponse) {
if (event.status === 401) {
this.user.logout();
}
}
})
);
} else {
const modified = req.clone({setHeaders: {'Authorization': 'JWT ' + localStorage.getItem('token')}});
return next.handle(modified)
.pipe(
tap(event => {
if (event instanceof HttpErrorResponse) {
if (event.status === 401) {
this.user.logout();
}
}
})
);
}
}
}
它处理响应的部分不起作用。基本上,我试图检查是否返回了401,然后如果有401,则自动注销用户。
答案 0 :(得分:1)
您需要使用catch
专门捕获错误响应。
RxJS 5及更低版本(或出于兼容性考虑,安装了rxjs-compact
的RxJS 6 +):
next.handle(modified).catch(errorResponse => {
// do something
})
没有rxjs-compact
的RxJS 6 +:
catch
已被删除,因为它是JS中的保留关键字。
next.handle(modified).pipe(
catchError(errorResponse => {
// do something
}))
或者,如果您仍然想使用pipe
和tap
,则tap
具有三个可选参数:下一个回调,错误回调和完整回调。
next.handle(modified).pipe(
tap(
event => {
if (event instanceof HttpResponse)
console.log('request succeeded');
},
error => {
if (error instanceof HttpErrorResponse) {
console.log('request failed');
}
}
));