简体   繁体   English

如何在使用 forkJoin 触发请求时取消请求 Rxjs、Angular

[英]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我有一组 6 http get 请求,无论它们在单击按钮时的顺序如何,我都必须发出这些请求。我为此目的使用forkJoin

<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.我做了一些研究并了解 switchMap 运算符有助于取消请求,但我不确定我将如何在这里使用它。

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我认为,您正在寻找的运算符是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. ExhaustMap 的旧版本是 flatMapFirst() 运算符,它从第一个映射的可观察对象传播数据,并且只有在完成之前丢弃所有其他可观察对象时才会转到下一个。

As this answer states:正如这个答案所说:

Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort() .大多数 jQuery Ajax 方法返回XMLHttpRequest (或等效的)object,因此您可以只使用abort()

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

//kill the request
xhr.abort()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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