Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel a HTTPRequest in Angular 2?

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);             }         ); }); 
like image 987
tom10271 Avatar asked Apr 08 '16 03:04

tom10271


People also ask

How to cancel specific HTTP request Angular?

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.

Can you cancel API call?

You may cancel any request made through API category by keeping a reference to the promise returned.

How do I cancel HTTP request?

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.


1 Answers

You can use the following simple solution:

if ( this.subscription ) {    this.subscription.unsubscribe(); } this.subscription = this.http.get( 'awesomeApi' )  .subscribe((res)=> {   // your awesome code.. }) 
like image 85
ErvTheDev Avatar answered Sep 22 '22 17:09

ErvTheDev