【发布时间】:2021-02-17 20:29:06
【问题描述】:
我有一个interceptor,它截获从200 OK 消息中收到的401 错误代码。
很遗憾,我无法修改 API 服务器以返回 401 错误而不是带有错误代码的 200 OK。
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
switchMap((result: any) => {
//401 unauthorized error message
if (result && result.body && result.body.isSuccess == false && result.body.errorCode == '401') {
return this.unAuthorizedError(request, next);
} else {
return next.handle(request);
}
}),
catchError((error) => {
if (error instanceof HttpErrorResponse) {
switch ((<HttpErrorResponse>error).status) {
case 401:
case 403:
return this.unAuthorizedError(request, next);
default:
break;
}
}
return throwError(error);
})
);
}
问题是每个请求都会发送两次,我认为这是可能,因为switchMap 方法返回next.handle(request)。
我试过tap方法
tap((result: any) => {
//401 unauthorized error message
if (result && result.body && result.body.isSuccess == false && result.body.errorCode == '401') {
return this.unAuthorizedError(request, next);
}
}),
只发送一次请求,但当令牌过期时,this.unAuthorizedError(request, next) 不会被调用。
【问题讨论】:
-
你试过
map吗?
标签: javascript angular rxjs request angular-http-interceptors