简体   繁体   中英

How to cancel requests incase of triggering them using forkJoin Rxjs , Angular

I have a set of 6 http get requests which I have to make irrespective of their sequence on a button click.I am using forkJoin for that purpose

<button click="getData()">Get Data</button>


getData(){

  const ids = [1,2,3,4,5,6];

  const obs = ids.map(id => this.http.get('<my url>/' + id)

  forkJoin(...obs).subscribe(res => console.log(res));

}

If a user clicks on the button multiple time, is there a way I could cancel previous uncompleted requests and only make new fresh calls to the backend?

I did some research and understood switchMap operator helps in cancelling requests but I am not sure how I would be using it here.

Please help

public subscription: Subscription;

getData(){

  const ids = [1,2,3,4,5,6];

  const obs = ids.map(id => this.http.get('<my url>/' + id)

  if(this.subscription){
     this.subscription.unsubscribe();
  }

  this.subscription = forkJoin(...obs).subscribe(res =>console.log(res))
}

I think, the operator you are looking for is ExhaustMap

The older version of ExhaustMap is the flatMapFirst() operator which propagates data from the first mapped observable, and it only goes to the next when it finishes discarding all the other observables before finishing.

As this answer states:

Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort() .

var xhr = $.ajax({
    type: "POST",
    url: "some.php",
    success: function(msg){
       alert("Done");
    }
});

//kill the request
xhr.abort()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM