Dániel Kis
Dániel Kis

Reputation: 2631

Cancel http request

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?

Upvotes: 0

Views: 3322

Answers (2)

ErvTheDev
ErvTheDev

Reputation: 4507

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..
})

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657338

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

this.httpSubscription = this.http.get(...).subscribe(...);
...
this.httpSubscription.unsubscribe();

Upvotes: 5

Related Questions