Search code examples
angularrxjsangular7

How to cancel API calls that take more than 10 ms to respond in interceptor


I have tried to implement this using takeUntil rxjs,

It will not cancel all API calls after a certain time when I click on the Call API button multiple times.

Stackblitz link - Code Example

Question 1 - As per above Stackblitz link, I can see it will cancel the API call in inspect network tab, but it will not print the console.log('called interceptor timeout') from the setTimeout in interceptor file for each request that cancel.

Question 2 - Any other best solution to handle this requirement?


Solution

  • As shown below, you can use the Timeout operator (Error will be thrown if an Observable fails to emit a value within the specified time period).

    import { timeout } from 'rxjs/operators';
    
    return next
      .handle(request)
      .pipe(
        timeout(1000 * 10),
        catchError(err => {
          ....
        }),
      )