问题描述
抽象问题:每次源Observable发出事件时,都需要触发一系列API调用和Angular服务。其中一些调用取决于先前的结果。
在我的示例中,源Observable startUpload$
触发了一系列依存调用。
使用解构可以这样写:
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,id }) => this.createPdfDocument(event,id)),id,pdfId }) => this.uploadBilderForPdf(event,pdfId,mergeMap(({ event,cloudId }) => this.closePdf(cloudId,event,pdfId)),cloudId }) => this.emitUploadDoneEvent(id,cloudId)),).subscribe()
它几乎像是一种命令式方法。但这有一些问题:
- 解构链在代码上重复,并且变得越来越
{ event,cloudId }
- 需要方法(例如
generateUploadId(event,headers)
)来接收所有先前的值,以便即使方法本身不需要它也可以将它们传递给下一个管道 - 需要内部可观测对象(在方法内)以映射值,以便其他管道阶段可以破坏它们:
_
private closePdf(cloudId,pdfId) {
return this.httpClient.post(...,{ headers } )
.pipe(
//...,map(() => ({ event,cloudId }))
)
}
如果编译器能够处理样板(例如使用async await
)来编写如下所示的代码(没有上述任何问题),那就太好了:
private startUpload(event: StartUploadEvent) {
const headers = this.getAuthenticationHeaders(event)
const id = this.generateUploadId()
this.emitUploadStartEvent(id,event)
const pdfId = this.createPdfDocument(event,id)
this.uploadBilderForPdf(event,id)
const cloudId = this.closePdf(headers,pdfId)
this.emitUploadDoneEvent(id,cloudId)
return cloudId
}
如何在链接的可观察对象之间传递结果而又没有我提到的问题?我错过了一个rxjs概念吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)