angular - NGRX/RXJS : How to recursively map observable streams into a single flat stream

标签 angular typescript rxjs reactive-programming ngrx

我当前在 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,其中包含用例的一个小示例以及我想要实现的目标。希望这能澄清一些事情:

https://stackblitz.com/edit/angular-ovpgsh

最佳答案

假设您已经有 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/

相关文章:

typescript - 如何在 rxjs 中创建一个在 1 秒后抛出错误的模拟 API 调用?

node.js - Node原生mongodb驱动连接池问题

angular - 在 redux/ngrx 应用架构中初始化模型对象的位置

javascript - 类型错误 : Cannot read property 'Autocomplete' of undefined in Angular 2

javascript - 无法在 eventReceived 事件中为 Angular 中的事件设置 ID

angular - 404在 Angular 4,nginx服务器和apache中的路由刷新

javascript - react 15, typescript 2.2.1。如何为功能/无状态组件转换类型?

javascript - Angular 6 解析始终未定义

Angular/Typescript Eval 和这个

angular - rxjs 发布重播 : reset on Error