抽象问题:每次源 Observable 发出和事件时,都需要触发一系列 API 调用和 Angular 服务。其中一些调用取决于以前的结果。
在我的示例中,源 ObservablestartUpload$触发了一系列依赖调用。
使用解构可以这样写:
this.startUploadEvent$.pipe(
concatMap(event => this.getAuthenticationHeaders(event)),
map(({ event, headers }) => this.generateUploadId(event, headers)),
tap(({ event, headers, id }) => this.emitUploadStartEvent(id, event)),
concatMap(({ event, headers, id }) => this.createPdfDocument(event, headers, id)),
concatMap(({ event, headers, id, pdfId }) => this.uploadBilderForPdf(event, pdfId, headers, id)),
mergeMap(({ event, headers, id, pdfId, cloudId }) => this.closePdf(cloudId, event, headers, id, pdfId)),
tap(({ event, headers, id, pdfId, cloudId }) => this.emitUploadDoneEvent(id, event, cloudId)),
).subscribe()
Run Code Online (Sandbox Code Playgroud)
它几乎读起来像是一种命令式方法。但它有一些问题:
{ …我一直在网上寻找解决方案,但找不到适合我的用户情况的任何解决方案。我正在使用MEAN堆栈(角度6),并且有注册表。我正在寻找一种对API执行多个HTTP调用的方法,每个方法都依赖于前一个方法返回的结果。我需要这样的东西:
firstPOSTCallToAPI('url', data).pipe(
result1 => secondPOSTCallToAPI('url', result1)
result2 => thirdPOSTCallToAPI('url', result2)
result3 => fourthPOSTCallToAPI('url', result3)
....
).subscribe(
success => { /* display success msg */ },
errorData => { /* display error msg */ }
);
Run Code Online (Sandbox Code Playgroud)
我需要使用哪种RxJS运算符组合来实现此目的?一种可能的解决方案是嵌套多个订阅,但是我想避免这种情况,并使用RxJS更好地实现。还需要考虑错误处理...
先谢谢了!