本文介绍了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中的请求是否已被取消
发布评论