【发布时间】:2021-01-24 19:24:41
【问题描述】:
我正在尝试更好地了解如何使用 RxJS 运算符来解决我遇到的特定问题。我实际上有两个问题,但它们足够相似。
我正在从 API 端点 /api/v3/folders/${folderId}/documents 获取一堆文档,并且我已经设置了具有执行该功能的服务,并处理所有身份验证等。
然而,这个文档对象数组没有有描述属性。为了获得描述,我需要在上一次调用的每个文档上调用 /api/v3/documents/${documentId}/。我的文档界面是这样的:
export interface Document {
id: number;
name: string;
description: string;
}
我想我需要使用mergeMap 来等待并获取文档,一些如何将描述添加到我的Document 界面并返回整个内容,但是我无法获得最终结果。
getDocuments(folderId: number) {
return this.docService.getDocuments(folderId, this.cookie).pipe(
map(document => {
document; // not entirely sure what to do here, does this 'document' carry over to mergeMap?
}),
mergeMap(document => {
this.docService.getDocument(documentId, this.cookie)
}) // possibly another map here to finalize the array?
).subscribe(res => console.log(res));
}
这可能看起来有点重复,但我发现的任何帖子都没有 100% 为我清除问题。
对于理解如何在第二次调用中正确使用数据并将其全部打包在一起的任何帮助,我们非常感谢非常。谢谢。
感谢@BizzyBob,这是带有编辑和解释的最终解决方案:
getDocuments(folderId: number) {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Context': this.cookie$
});
return this.docService.getDocuments(folderId, this.cookie$).pipe(
mergeMap(documents => from(documents)),
mergeMap(document => this.http.get<IDocument>(
this.lcmsService.getBaseUrl() + `/api/v3/documents/${document.id}`,
{ headers: headers }
).pipe(
map(completeDoc => ({...document, description: completeDoc.description}))
)),
toArray()
).subscribe(docs => {
this.documents = docs;
console.log(this.documents);
}
)
}
由于某种原因,我无法从第二个服务订阅中拨打pipe(),所以我最终不得不在那里拨打http.get。错误是“不能在类型订阅上使用 pipe()”,这有点令人困惑,因为我在第一次订阅时使用了 pipe()。我将此更改应用于更新行为主题的服务功能,并且运行良好。谢谢!
【问题讨论】:
-
@fridoo 这确实有点帮助,谢谢
-
是的,这是同一个问题。请注意,如果要保证最终
docs数组中的项目顺序与this.docService.getDocuments(folderId, this.cookie$)发出的数组中项目的顺序相同,则必须使用forkJoin方法。 -
啊,谢谢!我即将对实际数据进行更彻底的测试。希望一切正常。再次感谢!
标签: angular http rxjs observable mergemap