递归http

编程入门 行业动态 更新时间:2024-10-23 14:33:27
本文介绍了递归http-api调用后的消息订阅者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I want to fetch a list of nodes to create an array of said node objects in order to display an hierarchy. The based data/structure looks like this:

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,该API返回给定节点内的子级.我还尝试在REST结构中对该层次结构进行建模,因此调用看起来像这样:

You have a Root Node, with child nodes which also contain childs. Inclucing the ROOT node, there are 3 stages in the tree. I created an REST-API which returns the children inside the given node. I also tried to model this hierarchy inside my REST structure, so the calls look like this:

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

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

In order to build a tree I tried to use a recursive pattern, something like this:

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[]; }

推荐答案

您将需要在 subscribe()范围内设置 this.subject 值.因此,在设置值之前,它具有正确结构的完整列表.

You will need to set the this.subject value with in the subscribe() scope. So that way it has a complete list in correct structure before setting the values.

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; }

这将起作用,因为它会在有数据时设置主题的值.

That will work as it sets the value of the subject when it has data.

更多推荐

递归http

本文发布于:2023-10-31 07:27:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   http

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!