![](/img/trans.png)
[英]handle cancelled http request in angular httpclient interceptor
[英]Angular: How to know if request has been cancelled in HttpClient
要知道請求是否已完成,我會這樣做if (httpEvent instanceof HttpResponse)
。 同樣,如何知道HttpInterceptor
是否取消了請求? 下面是我的intercept
功能。
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.slimLoadingBarService.complete();
}
else {
if (this.requestsPending === 0)
this.flsLoaderService.stop();
}
}
}, () => {
this.slimLoadingBarService.complete();
// reset counter on error
this.requestsPending = 0;
this.flsLoaderService.stop();
});
}
我也有這個問題,這是我最近來的一個解決方案:
要知道請求是否被取消,你可以使用finally
運算符,例如:
let cancelled = true;
return next.handle(request).do(
undefined,
() => {
// error
cancelled = false;
},
() => {
// completed
cancelled = false;
},
).finally(
() => {
if (cancelled) {
// do things
}
},
);
最后我找到了解決方案
intercept(httpRequest: HttpRequest<any>, httpHandler: HttpHandler):
Observable<HttpEvent<any>> {
this.requestsPending++;
//...
return new Observable(observer => {
let sub = httpHandler.handle(httpRequest)
.pipe(tap(event => {
//... your logic
}))
.subscribe(event => observer.next(event));
return () => {
if (!sub.closed) {
this.requestsPending--;
sub.unsubscribe();
}
};
});
}
為了使它工作,我使用了上面兩種技術的混合,因為他們沒有為我開箱即用。 這是我的工作代碼:
// your increment logic here
return new Observable(observer => {
let isCanceled = true; << here
const sub = next.handle(req)
.pipe(
tap(
(rsp: HttpResponse<any>) => {
if (rsp.type === HttpEventType.Response) {
isCanceled = false;
// your decrement logic here
}
},
(rspError: HttpErrorResponse) => {
isCanceled = false;
// your decrement logic here
throwError(rspError); // re-throw same e
},
),
)
.subscribe(observer); // << here
return () => {
if (isCanceled) {
// your decrement logic here
sub.unsubscribe();
}
};
});
似乎angular忽略了中止事件。 以下是Angular資源: https : //github.com/angular/angular/blob/5.0.1/packages/common/http/src/xhr.ts
如果請求被中止,則返回的Observable會通知訂閱者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.