0

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?

Munchkin
  • 857
  • 5
  • 24
  • 51
  • entire code is available in this link, https://github.com/500tech/angular-tree-component/blob/master/example/cli/src/app/async/async.component.ts – Anto Antony Feb 28 '20 at 11:52
  • Apparently I don't quite understand how to implement it for my use case. – Munchkin Feb 28 '20 at 14:58

1 Answers1

2

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>
 `,
Anto Antony
  • 842
  • 6
  • 12
  • Do I understand this correctly: for each nested level there needs to be an extra API call for each single one? – Munchkin Mar 03 '20 at 11:27
  • @Munchkin I understood it in the same way. You always call the server when you go one step deeper. Did you try it? – H.Karatsanov Jan 04 '22 at 13:49
  • @H.Karatsanov I think I did, this question is almost 2 years old now, so I don't remember.. – Munchkin Jan 10 '22 at 08:18