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?

2

1 Answer 1

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>
 `,
Sign up to request clarification or add additional context in comments.

3 Comments

Do I understand this correctly: for each nested level there needs to be an extra API call for each single one?
@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 I think I did, this question is almost 2 years old now, so I don't remember..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.