Hi I am developing web application in Angular 5. I am generating tree like structure. I am following https://github.com/500tech/angular-tree-component/blob/master/example/cli/src/app/async/async.component.ts. I am making API call to get data dynamically and display as tree. My approach works fine with static data but it wont work with dynamic data getting after making http call.
Below code works with static data.
asyncChildren = [
{
name: 'child1',
hasChildren: true
}, {
name: 'child2'
}
];
getChildren(node: any) {
const newNodes = this.asyncChildren.map((c) => Object.assign({}, c));
return new Promise((resolve, reject) => {
setTimeout(() => resolve(newNodes), 1000);
});
}
In the above code when I call service instead of this.asyncChildren my code will not work. Below is my implementation.
getChildren(node: any) {
const newNodes = this.ChildTranslator().map((c) => Object.assign({}, c));
return new Promise((resolve, reject) => {
setTimeout(() => resolve(newNodes), 1000);
});
}
Above method will be called whenever there are child nodes. So Instead of this.asyncChildren I am making call to this.ChildTranslator method which make http service call and get JSON and convert the data in the required format. Below is the implementaion of ChildTranslator method.
public string ChildTranslator(){
this.nodeservice.GetChildNodes().subscribe(data=>{
this.asyncChildren= this.transformer(data);
return this.asyncChildren;
});
}
The transformer code.
public string transformer(data:any){
this.asyncChildren=[];
let results=data;
for (const key in results) {
if (results[key] instanceof Array) {
const containerTyp2 = {name: '', hasChildren: false,};
containerTyp2.name = key;
containerTyp2.hasChildren = true;
this.asyncChildren.push(containerTyp2);
} else {
const object = {name: ''};
const containerTyp1 = {name: '', children: []};
object.name = results[key];
containerTyp1.name = key;
containerTyp1.children.push(object);
this.asyncChildren.push(containerTyp1);
}
this.tree.treeModel.update();
}
return this.asyncChildren;
}
Above piece of code pops me the below error.
Cannot read property 'map' of undefined
Can someone help me to make this work? May I know what I am missing in the above code? Any help would be greatly appreciated. Thank you.
ChildTranslator()does not return a value.