首页 > 解决方案 > 如何实现这个角树组件异步数据代码?

问题描述

我在实现这个https://angular2-tree.readme.io/docs/async-data-1时遇到了麻烦。如何将 OnInit 中的以下代码重写为文档中的异步代码?:

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

另请参考这个问题How to store HttpClient GET fetched data into a variable?

标签: jsonangularangular-httpclientangular-tree-component

解决方案


以异步方式制作树意味着,您可以在其父节点展开时获取它的子节点,而不是首先加载所有项目。

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

  nodes: any[] = [];

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

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

所以拿到数据后,nodes数组应该是这样的,

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

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

接下来我们需要为 angular-tree-component 提供选项,这样它就可以了解在哪里获取子项。

 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 后,lib 将调用 getChildren,并且它的子节点将附加到它。

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

推荐阅读