等待所有待处理的请求得到解决,并从最后一个获得价值

时间:2018-11-21 08:36:19

标签: angular rxjs

我在Angular应用程序中有一个方法getData(),每次更改表中的asc > desc排序时都会点击一次。如果我连续单击10次,则将发出10个get请求,并且每次请求被解决时,数据都会分配到表,因此它闪烁直到最后一个请求。如何仅等待上一个请求的数据而忽略另一个请求?

 this.getData() {
   this.endpointsService.getData(reqParams).pipe(
      takeUntil(this.ngUnsubscribe$)  
   ).subscribe((data) => {
      this.data$.next(data);
   }
 }

data $与* ngFor一起使用

*ngFor="let item of (data$ | async)">

3 个答案:

答案 0 :(得分:1)

重点不是自己直接致电getData(),而是创建主题并在其中填充搜索查询。然后,您可以使用“主题”创建一个可以取消订阅先前请求的链:

private s$ = new Subject();
private result$ = s$.pipe(
  takeUntil(this.ngUnsubscribe$),
  switchMap(reqParams => this.endpointsService.getData(reqParams)),
);

getData(reqParams) {
  this.s$.next(reqParams);
}

然后在您的模板中:

*ngFor="let item of (result$ | async)">

switchMap运算符将从其源发出的每个发射中取消其内部Observable的订阅。

理想情况下,您也可以在debounceTime()之前使用switchMap,以避免产生太多请求。

答案 1 :(得分:0)

如果我理解正确,您想在用户交互后等待一段时间以使表格不更改排序,然后应用该功能?

您可以使用let object = { "statusCode": 200, "body": [{ "id": "3", "externalId": "yehudakala4", "status": "active", "createdAt": "2018-11-14T08:36:50.967Z", "updatedAt": "2018-11-14T08:36:50.967Z", "firstName": "yehu", "lastName": "da", "email": "ye@g.com" }], "headers": { "x-powered-by": "Express", "access-control-allow-origin": "*", "content-type": "application/json; charset=utf-8", "content-length": "189", "etag": "W/\"bd-Emx3/KChQLzf9+6bgFSHXPQgDTM\"", "date": "<<Masked>>", "connection": "close" }, "request": { "uri": { "protocol": "http:", "slashes": true, "auth": null, "host": "user-management-service.dev.local:4202", "port": "4202", "hostname": "user-management-service.dev.local", "hash": null, "search": "?username=yehudakala4", "query": "username=yehudakala4", "pathname": "/v1/users", "path": "/v1/users?username=yehudakala4", "href": "http://user-management-service.dev.local:4202/v1/users?username=yehudakala4" }, "method": "GET", "headers": { "Content-Type": "application/json", "accept": "application/json", "content-length": 2 } } } let key = "protocol"; let value = "http:"; let x; let res = false; let matches = []; function findValue(obj, key) { if (obj.hasOwnProperty(key)) { matches.push(obj[key]); } for (k in obj) { if (Array.isArray(obj[k])) { obj[k].forEach(el => findValue(el, key)); } else if (obj[k] && typeof obj[k] == "object") { findValue(obj[k], key); } } } findValue(object, key); let rs = matches.every(m => m == value); console.log(rs);

debounceTime()

this.getData() { this.endpointsService.getData(reqParams).pipe( takeUntil(this.ngUnsubscribe$), debounceTime(1000), distinctUntilChanged() ).subscribe((data) => { this.data$.next(data); } } 将等待排序保持不变1秒钟,然后将获取数据

参考:https://stackoverflow.com/a/50740491/4091337

答案 2 :(得分:0)

您可以使用Delay运算符来实现。

endpointsService:

getData(){
  return this.http.get(url).pipe(
    delay(500)
  )
}

组件:

this.getData() {
   this.endpointsService.getData(reqParams).pipe(
      takeUntil(this.ngUnsubscribe$)
   ).subscribe((data) => {
      this.data$.next(data);
   }
 }