【问题标题】:Recursive HTTP calls with RxJs to populate a tree structure使用 RxJ 进行递归 HTTP 调用以填充树结构
【发布时间】:2022-01-18 21:54:00
【问题描述】:

我有以下数据结构

export interface Node {
  id: string;
  name: string;
  children?: Node[];
}

我想在 RxJs 中使用递归 HTTP 调用填充由 Nodes 组成的树。

我尝试了this question 上提出的解决方案,但无法成功。 HTTP 调用正确,但 Observable 永远不会完成,因此订阅不会被执行。

这是我一直坚持的代码:

ngOnInit(): void {
  this.service.getById(this.id)
     .pipe(mergeMap(s => this.getChildren(s)))
     .subscribe(res => {
        // IT NEVER GETS HERE
     });
}

getChildren(node: Node): Observable<Node> {
  return this.service.getChildren(node.id).pipe(
    mergeMap(children => forkJoin(children.map(node => this.getChildren(node)))),
    map(children => ({ ...node, children }))
  );
}

我做错了什么? 请帮忙,谢谢建议。

【问题讨论】:

    标签: angular http recursion rxjs observable


    【解决方案1】:

    递归需要一个退出条件。您可以使用 RxJS iif 函数之类的东西来强制执行条件。

    在下面的sn-p中,检查参数nodeid属性是否定义。

    免责声明:代码仅提供了一种找到解决方案的方法。下面的 sn-p 未经测试,可能无法按预期工作。

    import { Observable, forkJoin, iif, of } from 'rxjs';
    
    ngOnInit(): void {
      this.service.getById(this.id).pipe(
         mergeMap(s => this.getChildren(s))
      ).subscribe(
        res => {
          // handle response
        },
        error => {
          // handle errors
        }
      );
    }
    
    getChildren(node: Node): Observable<Node> {
      return iif(
        () => !!node.id,                         // <-- check if `node.id` is defined
        this.service.getChildren(node.id).pipe(  // <-- `id` property is defined
          forkJoin(children.map(node => this.getChildren(node)),
          map(children => ({ ...node, children }))
        ),
        of(node)                                 // <-- `id` property is undefined
      );
    }
    

    【讨论】:

    • 您忘了将mergeMap 添加为管道中的第一个运算符,对吧?无论如何,我尝试了您的解决方案,但它不起作用。它实际上完成了流,但只是在第一个节点上,所以结果只是第一个节点本身。如果我将iif 中的条件更改为!!node.children &amp;&amp; node.children.length &gt; 0,我会得到与我发布的相同的原始结果:流永远不会完成
    猜你喜欢
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多