【问题标题】:Serial and parallel HTTP requests with Angular 5 and RxJS使用 Angular 5 和 RxJS 的串行和并行 HTTP 请求
【发布时间】:2018-03-26 04:18:02
【问题描述】:
<button (click)="onSaveItems()">Save</button>

this.selectedItems = [ 
  {'id': 1, name: 'A'},
  {'id': 2, name: 'B'},
  {'id': 3, name: 'C'},
  {'id': 4, name: 'D'},
  {'id': 5, name: 'E'}
]

this.apiService1.deleteAllItems()
this.apiService2.addItem(itemId)
this.apiService3.addItemLog(itemId)
this.apiService4.addFlag()

当用户点击保存按钮时,我想:

  1. 调用apiService1并删除所有项目
  2. 如果步骤 1 成功,我想调用 apiService2 来添加选中项
  3. 如果步骤 2 成功,我想调用 apiService3 为该特定项目添加项目日志
  4. 对 selectedItems 中的每个项目重复步骤 2.i 3.
  5. 如果所有项目日志都添加成功我想调用 apiService4

(请注意,我无法更改 API 逻辑)

有没有办法用 Angular 和 RxJS 做到这一点?

【问题讨论】:

  • 我不知道this.apiService1 的实现,但你会想订阅rxjs 中的每个结果。所以例如..deleteAllItems().subscribe(() => ... 下一步...)

标签: angular rxjs


【解决方案1】:

我假设您使用的是 angular http 客户端,因此是 RxJs Observables。

如果是这种情况,那么您需要做的就是按照这些思路进行操作

function processItem(item) {
  return this.apiService2.addItem(item)
          .switchMap(itemId => this.apiService3.addItemLog(item))
}

function deleteAllAndThenProcess() {
  return this.apiService1.deleteAllItems()
             .switchMap(() => Observable.from(this.selectedItems)
             .mergeMap(item => processItem(item))
}

function doEverything() {
   deleteAllAndThenProcess()
   .last(() => this.apiService4.addFlag())
   .subscribe(
     () => console.log('processing completed'),
     err => console.error(error)
   )
}

详细信息可能有误(例如,我已将 itemId 替换为 item 作为 apiService2.addItemapiService3.addItemLog 的参数,但希望这可以让您了解如何链接可观察对象以实现您想要实现的目标。让我补充说,这是 Observable 的强大功能的典型用例。

您可能希望查看 this 以了解有关与您的非常相似的用例的更多详细信息,即使它谈论的是节点而不是 Angular。

【讨论】:

    猜你喜欢
    • 2017-06-13
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多