问题
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