角度拦截器,处理HTTP错误并重试 [英] Angular interceptor, handle HTTP Error and retry
本文介绍了角度拦截器,处理HTTP错误并重试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个基本的JWT系统和一个拦截器,它可以检查请求是否由于未经授权而失败。
import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {AuthService} from '../services/auth.service';
import {catchError, retryWhen} from 'rxjs/operators';
@Injectable()
export class AuthenticationErrorInterceptor implements HttpInterceptor {
private readonly _authService: AuthService;
constructor(authService: AuthService) {
this._authService = authService;
}
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({headers: req.headers});
return next.handle(authReq)
.pipe(
catchError((err) => this._handleAuthError(err)),
retry(3)
);
}
private _handleAuthError(error: HttpErrorResponse): Observable<any> {
if (error.status === 401 || error.status === 403) {
return this._authService.authenticate();
}
return throwError(error);
}
}
如果请求失败,则我希望在调用this._authService.authenticate();
之后重新发送请求。它将重新进行身份验证,因为错误处理会迫使它重新进行身份验证,但随后它不会召回导致应用程序失败的请求,直到我刷新浏览器。
如何让我的警卫再次尝试该请求?
我也尝试使用retryWhen
,但得到相同/相似的结果。
推荐答案
在重新对会话进行身份验证后,在HTTp处理程序上调用.Next。理想情况下,您应该从您的身份验证方法返回一个身份验证令牌,然后可以将该令牌追加到请求auth标头上。
import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {AuthService} from '../services/auth.service';
import {catchError, retryWhen} from 'rxjs/operators';
@Injectable()
export class AuthenticationErrorInterceptor implements HttpInterceptor {
private readonly _authService: AuthService;
constructor(authService: AuthService) {
this._authService = authService;
}
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401 || error.status === 403) {
return this._authService.authenticate()
.pipe(
mergeMap((token) => next.handle(req.clone({
headers: req.headers.set(AUTH_TOKEN_NAME_HERE, token)
})))
);
}
return throwError(error);
})
);
}
}
这篇关于角度拦截器,处理HTTP错误并重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文