我当前在 Ngrx Store 中有以下对象结构:
class Case {
id: string; // an id to uniquely identify the Case
type: string; // an id to identify the type of the Case
links: { [ type: string ]: string }; // a dictionary of links to the current Case.
// the keys are the type of the Case, and the values are the actual id's of the linked Cases.
// These linked cases are in the same store as the Parent Case
}
我可以使用以下方法从商店检索此案例
getCase(caseId: string): Observable<Case>
来自caseService
我需要创建一个方法,该方法采用案例 ID 并在商店中查询案例及其所有链接。对于所有链接的案例,需要递归地检索这些链接。
此方法需要按以下结构返回案例及其所有链接:
class CaseLinks {
case: Case;
links: { type: string, items: CaseLinks[] }[]
}
这意味着我需要 getCaseLinks(baseCaseId: string): Observable<CaseLinks>
的方法签名
无论如何,我可以从商店中查询一个项目,并根据案例中的链接,递归地查询商店中的链接案例,并将所有 Observables 的结果返回到一个单一的、平坦的、可观察的流中。
下面我添加了一个 Stackblitz,其中包含用例的一个小示例以及我想要实现的目标。希望这能澄清一些事情:
最佳答案
假设您已经有 getCase 和 getLink 选择器,请尝试以下代码:
function getCaseLinks(caseId: string) {
return this.getCase(caseId).pipe(
mergeMap(case => combineLatest(case.links.map(link => getLink(link.id))).pipe(
map(items => ({
case,
links: { type: string, items }
}))
))
)
}
关于angular - NGRX/RXJS : How to recursively map observable streams into a single flat stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60166744/