简体   繁体   English

Angular NgRx Effect concatMap 基于条件的多个HTTP请求

[英]Angular NgRx Effect concatMap multiple HTTP requests based on condition

I have an action which is mapped to HTTP request via concatMap method because I need those HTTP requests to be sequenced.我有一个通过concatMap方法映射到 HTTP 请求的操作,因为我需要对这些 HTTP 请求进行排序。 I'd like to improve this behavior by sequencing only HTTP requests with same object ID that's sent in the action.我想通过仅对操作中发送的具有相同对象 ID 的 HTTP 请求进行排序来改进此行为。

This is the code I have that's working, but making all the requests sequentials.这是我正在运行的代码,但是使所有请求都是顺序的。 I am using it for inline editing of records and I want to make it that if user changes value1 for record with ID:1 and then changes value2 for ID:1 these calls will be sequential, but if he changes value1 for record with ID:2 in the meantime then it would do the save request for record with ID:2 in parallel with those save requests for record with ID:1.我将它用于记录的内联编辑,并且我希望如果用户更改 ID 为value1的记录的value1 ,然后更改 ID 的value2为 ID:1,这些调用将是顺序的,但如果他更改了 ID 的记录的value1 : 2 同时,它将对 ID:2 的记录的保存请求与 ID:1 的记录的保存请求并行执行。 Is this possible with some map method?这可以用一些地图方法吗?

@Effect()
saveEffect = this.actions.pipe(
  ofType(saveAction),
  concatMap(action => this.service.save(action.oID, action.saveData)
    .pipe(
      map(...),
      catchError(...)
    )
  )
);

You can use groupBy to group your actions by id.您可以使用groupBy按 id 对您的操作进行分组。 This operator will emit every incoming action on an Observable for its specific group.此操作符将针对其特定组发出 Observable 上的每个传入操作。

saveEffect = this.actions.pipe(
  ofType(saveAction),
  groupBy(action => action.oID),
  mergeMap(group$ => group$.pipe(
    concatMap(action => this.saveAction(action))
  ))
);

saveAction(action): Observable<any> {
  return this.service.save(action.oID, action.saveData).pipe(
    map(...),
    catchError(...)
  )
}

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

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