【问题标题】:Message Subscribers after recursive http-api calls递归 http-api 调用后的消息订阅者
【发布时间】:2017-08-29 13:39:25
【问题描述】:

我想获取节点列表以创建所述节点对象的数组,以显示层次结构。基于的数据/结构如下所示:

ROOT (ID=1)
|--NODE (ID=2)
|  └--NODE (ID=4)
|     └--NODE (ID=11)
└--NODE (ID=3)
   |--NODE (ID=5)
   |--NODE (ID=6)
   |--NODE (ID=7)
   └--NODE (ID=8)
      |--NODE (ID=9)
      └--NODE (ID=10)  

您有一个根节点,其子节点也包含子节点。包括 ROOT 节点,树中有 3 个阶段。我创建了一个 REST-API,它返回给定节点内的子节点。我还尝试在我的 REST 结构中对该层次结构进行建模,因此调用如下所示:

TYPE        PATH                      RESULT CHILD IDs
GET         /1/nodes                  2, 3
GET         /1/nodes/2/nodes          4
GET         /1/nodes/3/nodes          5, 6, 7, 8
GET         /1/nodes/3/nodes/8/nodes  9, 10 

为了构建一棵树,我尝试使用递归模式,如下所示:

    this.subject.next(this.getNodes('/1/nodes'); /*root-uri*/

    getNodes(uri) {
      const nodeList: Node[] = [];
      http.get(path).subscribe(data => {
        for(const obj of data.json()) {
            let node = new Node();
            //map data to Node e.g node.is = data.id

            //get the children with the nested call
            node.children = getNodes(uri + '/' + node.id + '/nodes'); 
            nodeList.push(node);
        }
    }
    return nodeList;
}  

所以我的问题是:
如何从递归 http 调用创建节点对象数组并向订阅者发送消息,以便订阅者仅接收正确结构的完整节点数组


编辑

这就是节点模型的样子

export class Node {
  uuid: string;
  label: string;
  parentID: string;
  version: number;
  addableFlag: boolean;
  sectionFlag: boolean;
  children: Node[];
}

【问题讨论】:

  • 您正在以同步方式返回 nodeList,这将不起作用。
  • @Salketer 你能告诉我一个例子如何正确地做到这一点吗?

标签: javascript angular recursion


【解决方案1】:

您需要在subscribe() 范围内设置this.subject 值。这样,在设置值之前,它就有一个结构正确的完整列表。

this.getChildren('/1/nodes'); /*root-uri*/

getNodes(uri) {
    const nodeList: Node[] = [];
    http.get(path).subscribe(data => {
        for (const obj of data.json()) {
          let node = new Node();
          //map data to Node e.g node.is = data.id

          //get the children with the nested call
          node.children = getNodes(uri + '/' + node.id + '/nodes');
          nodeList.push(node);
        }
        this.subject.next(nodeList); /*root-uri*/
    }
      // Return would send empty data as this line get executed before data arrives
      // return nodeList;
}

这将起作用,因为它会在有数据时设置subject 的值。

【讨论】:

  • 如何将子节点添加到子数组中? node.children = getNodes(uri) 行 deosn´t 工作,因为 node.children 正在接受 Node 数组,但该方法不返回任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 2017-11-08
  • 2019-04-20
相关资源
最近更新 更多