如何实现此角度树组件异步数据代码? [英] How to implement this angular-tree-component async data code?

查看:85
本文介绍了如何实现此角度树组件异步数据代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在实施此 https://angular2-tree.readme时遇到麻烦.io/docs/async-data-1 .如何从OnInit重写以下代码以使其与文档中的内容一样异步?:

I am having trouble implementing this https://angular2-tree.readme.io/docs/async-data-1 . How do I rewrite the following code from OnInit to be async like in the documentation?:

this.client.get(API_URL, this.httpOptions).subscribe(
  (res) => { this.nodes.push(res) },
  (error) => { this.handleError(); }
);

另请参阅此问题如何将HttpClient GET提取的数据存储到变量中?

推荐答案

使树成为asyn意味着,您可以在其父节点扩展时获取其子级,而不是先加载所有项.

Making a tree as asyn means, you can fetch it's childrens when their parent node expands rather than loading all the items at first.

所以首先您将创建节点数组,

So first you will create nodes array,

  nodes: any[] = [];

例如,在ngOnInt生命周期中,您只能推送顶级节点,

And in ngOnInt lifecycle, you can just push only the top level nodes, for example,

ngOnInit() {
  this.client.get(API_URL_TO_FETCH_PARENT_NODES, this.httpOptions).subscribe(
    (res) => { this.nodes.push(res) },
    (error) => { this.handleError(); }
  );
}

因此,在获取数据之后,nodes数组应该是这样的,

So after getting the data, nodes array should be like this,

    [
      {
        name: 'root1',
        hasChildren: true
      },
      {
        name: 'root2',
        hasChildren: true
      },
      {
        name: 'root3'
      }
    ];

hasChildren属性也应该来自后端api,这样,只有组件才能理解该特定节点具有子节点,并且需要从另一个API提取.

So the hasChildren property should also come from the backend api, that way only the component can understand that this particular node having childrens and need to fetch from another API.

接下来,我们需要提供angular-tree-component的选项,以便它可以了解在何处获取子代.

Next we need to provide the options to angular-tree-component, So it can understand where to fetch the children.

 options: ITreeOptions = {
    getChildren: this.getChildren.bind(this),
    useCheckbox: true
  };

 getChildren(node: any) {
   return this.client.get(API_URL_TO_FETCH_CHILD_NODES_BY_PARENTID, this.httpOptions)
  }

一旦展开父节点root1,则getChildren将被lib调用,它的子节点将追加到子节点上.

Once you expand a parent node root1, the getChildren will get called by the lib and it's children will append to it.

 template: `
    <tree-root #tree [options]="options" [nodes]="nodes"></tree-root>
 `,

这篇关于如何实现此角度树组件异步数据代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆