How to implement this angular-tree-component async data code?

不羁岁月 提交于 2020-04-17 20:40:13

问题


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

Please also refer to this question How to store HttpClient GET fetched data into a variable?


回答1:


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

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

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

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

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.

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

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>
 `,


来源:https://stackoverflow.com/questions/60450560/how-to-implement-this-angular-tree-component-async-data-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!