How to cancel a HTTPRequest in Angular 2?
I know how to reject the request promise only.
return new Promise((resolve, reject) => { this.currentLoading.set(url, {resolve, reject}); this.http.get(url, {headers: reqHeaders}) .subscribe( (res) => { res = res.json(); this.currentLoading.delete(url); this.cache.set(url, res); resolve(res); } ); });
Cancel a Request - Rangle.io : Angular Training. Cancelling an HTTP request is a common requirement. For example, you could have a queue of requests where a new request supersedes a pending request and that pending request needs to be cancelled. To cancel a request we call the unsubscribe function of its subscription.
You may cancel any request made through API category by keeping a reference to the promise returned.
We can use the AbortController object and the associated AbortSignal with the Fetch API to make cancelable HTTP requests. Once the AbortSignal is sent, the HTTP request is canceled and won't be sent if the cancellation signal is sent before the HTTP request is done.
You can use the following simple solution:
if ( this.subscription ) { this.subscription.unsubscribe(); } this.subscription = this.http.get( 'awesomeApi' ) .subscribe((res)=> { // your awesome code.. })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With