0

In jQuery ajax there's a way to abort ajax queries:

var xhr = $.ajax({ ... });

when user wants to abort the operation or navigates to other page in a single page app I can call

xhr.abort();

In angular2-http api I cannot find any possibility to abort the query as it uses rxjs.

Is there a way to abort the ajax query in angular2?

Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
Dániel Kis
  • 1,841
  • 3
  • 24
  • 43
  • Possible duplicate of [How to cancel a subscription in Angular2](http://stackoverflow.com/questions/34442693/how-to-cancel-a-subscription-in-angular2) – Günter Zöchbauer Mar 21 '16 at 05:55

2 Answers2

4

When you subscribe, you get a subscription you can use to unsubscribe

this.httpSubscription = this.http.get(...).subscribe(...);
...
this.httpSubscription.unsubscribe();
Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
1

For a simple solution you can use the following, but you can also use .switchMap rxjs method..

if ( this.subscription ) {
   this.subscription.unsubscribe();
}
this.subscription = this.http.get( 'awesomeApi' )
 .subscribe((res)=> {
  // your awesome code..
})
ErvTheDev
  • 4,117
  • 2
  • 15
  • 19
  • what if the API calls are in a loop this.http.get( 'awesomeApi' ) .subscribe((res)=> { // your awesome code.. }) – indra257 May 24 '17 at 19:12
  • track of the last subscription (api call) .. if (special condition) { kill loop and unsubscripte last subscription } please provide more code if you need help – ErvTheDev May 25 '17 at 08:55