[英]How to handle/detect canceled requests in http interceptor Angular?
How do I handle cancelled requests in http interceptor?如何在 http 拦截器中处理取消的请求? I have tried various methods from SO, but none of them seem to catch it.
我尝试了 SO 的各种方法,但似乎没有一个能抓住它。
This is how my interceptor is,我的拦截器是这样的
public intercept(req: HttpRequest<any>, next: HttpHandler) { const xyz = this._cookieService.get('xyz'); const abc = this._cookieService.get('abc'); let authReq; if (jwt === "undefined" || jwt === undefined) { authReq = req.clone({ headers: req.headers.set('Authorization', xyz) }); } else { authReq = req.clone({setHeaders: { Authorization: 'bearer ' + abc } }); } return next .handle(authReq) .pipe( catchError((err: HttpErrorResponse) => this.catchErrorHandler(err)) ); }
I have tried the do
, finalize
methods as well.我也尝试过
do
, finalize
方法。 Its that, my auth expires, and all the requests after that just collapse one by one, and the page breaks.就是这样,我的身份验证过期了,之后的所有请求都一一折叠,分页符。 I would like to handle it with code, so that the page doesn't break.
我想用代码处理它,这样页面就不会中断。 Methods I have tried: https://stackoverflow.com/a/50620910/6630504 https://stackoverflow.com/a/55756885/6630504
我尝试过的方法: https : //stackoverflow.com/a/50620910/6630504 https://stackoverflow.com/a/55756885/6630504
There is an RxJS operator called finalize .有一个名为finalize的 RxJS 操作符。
Returns an Observable that mirrors the source Observable, but will call a specified function when the source terminates on complete or error.
返回一个镜像源 Observable 的 Observable,但是当源在完成或错误时终止时将调用指定的函数。 The specified function will also be called when the subscriber explicitly unsubscribes.
当订阅者明确取消订阅时,也会调用指定的函数。
return next
.handle(authReq)
.pipe(
catchError((err: HttpErrorResponse) => this.catchErrorHandler(err)),
finalize(() => console.log('finalize'))
);
Try this interceptor:试试这个拦截器:
@Injectable()
export class RequestInterception implements HttpInterceptor {
public constructor() { }
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token = '';
const currentLanguage = 'en';
let headers;
if (token) {
headers = new HttpHeaders({
"X-MDM-Token": token,
"Accept-Language": currentLanguage
});
}
request = request.clone({
headers: headers,
url: request.url || environment.serverUrl
});
return next.handle(request).pipe(
map((event: any) => {
if (event.status < 200 || event.status >= 300) {
return Observable.throw(event);
}
return event;
}),
catchError((response: HttpErrorResponse, request) => {
switch (response.status) {
case 401:
//
break;
}
return throwError("Ошибка сервера RequestInterception!");
})
);
}
}
If client canceled http request you will get 499 http code, it will be caught by:如果客户端取消了 http 请求,您将获得 499 http 代码,它将被捕获:
if (event.status < 200 || event.status >= 300) {
return Observable.throw(event);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.