-1

I am working in one angular project that have call API in a sequence and API response is stored in single global variable.

My API flow is look like below : enter image description here

Explaination :

  1. User click on first request button, then first request is send to server.
  2. Before display data of first request in html, user click on another button and make second API request.
  3. here response of first request not returned by server yet and make another request.
  4. after that, response of second request is occur first.
  5. then result of first request is occur.
  6. At that time, all result will merge. but expected output is like this :
  7. cancel first request and only display result of second request.

Is there any way to cancel all pending request first then make another request. Please help me.

Mayur Kukadiya
  • 2,461
  • 1
  • 25
  • 58

1 Answers1

0

Here is how you can handle this, with any of the followings :

a) Better approach would be to use a spinner with overlay, since you must make the user aware that he has already triggered the request and is awaiting for the response

b) With Observables you can use "SwitchMap" to cancel pending subscriptions, refer: SwitchMap

c) Inside your interceptor, store all incoming requests as key-value pair, if any request with same key comes again, simply reject it, however this will cancel the subsequent similar requests.

Cheers (y)

yanky_cranky
  • 1,303
  • 1
  • 11
  • 16
  • Thank you for reply. I am implement takeUntil pipe in http request suggested by : https://stackoverflow.com/questions/46068908/how-to-cancel-unsubscribe-all-pending-http-requests-angular-4 I can't use first method of overlay because I don't want to block user. – Mayur Kukadiya Jun 13 '19 at 08:07
  • i would prefer, switchmap over takeUnitl since apart from the overheads in takeUntil, you might run in issues like leaks etc, whereas switchMap specifically designed to serve this purpose to work only on one subscription and cancel others. – yanky_cranky Jun 13 '19 at 08:41
  • 1
    sorry for late reply, I will try to use switchmap. – Mayur Kukadiya Jun 17 '19 at 03:35