我试图更好地了解如何使用 RxJS 运算符来解决我遇到的特定问题。我实际上有两个问题,但它们很相似。
我正在从 API 端点获取一堆文档/api/v3/folders/${folderId}/documents
我已经设置了具有执行此操作的功能的服务,并处理所有身份验证等。
然而,这个文档对象数组确实not具有描述属性。为了获得描述,我需要打电话/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% 为我解决问题。
对于理解如何在第二次调用中正确使用数据并将其全部包装在一起的任何帮助都非常重要much赞赏。谢谢。
感谢@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
打电话到那里。错误是“无法在类型订阅上使用 pipeline()”,这有点令人困惑,因为我正在使用pipe()
在第一次订阅时。我将此更改应用到我的服务功能中,该功能更新了行为主题,并且运行完美。谢谢!