1

Angular cancels http requests very fast and I want to intercept those cancelled requests. Is it possible to capture cancelled requests in the interceptor? Below is a fragment of my interceptor code, where I want to catch cancelled request.

  intercept(req: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>> {
    this.onStartRequest();
    // Pass the cloned request instead of the original request to the next handle
    return next.handle(req).do(
      (event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
         // do something
        }
      },
      (err: any) => {
        if (err instanceof HttpErrorResponse) {
          // do something
        }
      }
    );
  }
3

2 Answers 2

3

Did you try with the finalize event?

return next.handle(req).pipe(
  finalize(() => {
    // request completes, errors, or is cancelled
  })
);
Sign up to request clarification or add additional context in comments.

1 Comment

How do I figure out which request, got canceled in finalize? Does it have any specific key in it which shows that the particular request got canceled?
0

You have to use the catchError RxJs operator when you use the next Handler, here's the code:

intercept(req: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>> {
    this.onStartRequest();
    // Pass the cloned request instead of the original request to the next handle
    return next.handle(req).do(
      (event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
         // do something
        }
      })
      .catchError((err: HttpErrorResponse) => {
        // Handle errors
      });
  }

PS: Don't forget to import the catchError operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.