Angular:如何知道HttpClient中的请求是否已被取消

编程入门 行业动态 更新时间:2024-10-20 15:50:02
本文介绍了Angular:如何知道HttpClient中的请求是否已被取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

要知道请求是否已完成,请执行if (httpEvent instanceof HttpResponse).同样,如何知道HttpInterceptor中的请求是否被取消?下面是我的intercept函数.

To know if a request has completed, I do if (httpEvent instanceof HttpResponse). Likewise, how to know if a request is cancelled in HttpInterceptor? Below is my intercept function.

intercept(httpRequest: HttpRequest<any>, httpHandler: HttpHandler): Observable<HttpEvent<any>> { this.requestsPending++; if (this.typeAheads.includes(httpRequest.url.split('/').pop())) this.slimLoadingBarService.start(); else this.flsLoaderService.start(); return httpHandler.handle(httpRequest) .do((httpEvent: HttpEvent<any>) => { if (httpEvent instanceof HttpResponse) { // decrementing counter on each request return this.requestsPending--; if (this.typeAheads.includes(httpEvent.url.split('/').pop())) { if (this.requestsPending === 0) this.slimLoadingBarServiceplete(); } else { if (this.requestsPending === 0) this.flsLoaderService.stop(); } } }, () => { this.slimLoadingBarServiceplete(); // reset counter on error this.requestsPending = 0; this.flsLoaderService.stop(); }); }

推荐答案

我也遇到了这个问题,这是我最近遇到的一个解决方案:

I have also had this problem and that's a solution to which I've came recently:

要知道请求是否已取消,可以使用finally运算符,例如:

to know if a request was cancelled you can use finally operator, heres example:

let cancelled = true; return next.handle(request).do( undefined, () => { // error cancelled = false; }, () => { // completed cancelled = false; }, ).finally( () => { if (cancelled) { // do things } }, );

更多推荐

Angular:如何知道HttpClient中的请求是否已被取消

本文发布于:2023-11-27 09:12:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637450.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:已被   Angular   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!