Reputation: 725
my goal is to simply create a treeview using this https://www.primefaces.org/primeng/#/tree component.
I currently have a small service with this method
TS:
getMenuDetails(parentID: number) {
let url = this.serverURL + 'api/Nodes/' + parentID;
console.log(url);
return this.http.get(url)
.map(res => {
return <TreeNode[]>res.json()
})
}
I'm calling this service in my component like this
TS:
export class TreeViewComponent implements OnInit {
mainTree: number = 1;
rootDetails: TreeNode[];
constructor(private projectService: ProjectRoleService) { }
ngOnInit() {
this.projectService.getMenuDetails(this.mainTree)
.subscribe(res => this.rootDetails = res)
console.log(this.rootDetails);
};
My problem is that I'm not able to display the data in
this.rootDetails
HTML:
<p-tree [value]="rootDetails"></p-tree>
Error:
Cannot find a differ supporting object '[object Object]' of type 'Wurzel'. NgFor only supports binding to Iterables such as Arrays.
Does anyone know how to fix this?
EDIT 1:
This is how my data returned from the service looks like
{
descr: "WurzelNode"
id: 1
lvl: 1
name: "Wurzel"
parentid: 0
position: 1
rootid:1
}
Upvotes: 1
Views: 3184
Reputation: 11
In this specific case you were declaring your result as array,
rootDetails: TreeNode[];
but what you fed into [value]
is not an array according to your later explanations.
So switching to
this.projectService.getMenuDetails(this.mainTree)
.subscribe(res => this.rootDetails = [res]
instead will do the trick I assume.
Upvotes: 1
Reputation: 4179
loadData(){
this.loadDataService.getLazyFiles(
this.URL,
(response:any) => {
this.config.nodes = response.map((elem) => <TreeNode>{
label : `${elem.title}_MyValue`,
data: elem.id,
"expandedIcon": "fa fa-folder-open",
"collapsedIcon": "fa fa-folder",
leaf:false,
type:"1",
});
}, (error) => {
console.log(error);
});
}
Apart from template as mentioned above, another approach as mentioned by @Antikhippe, was to map the response of the JSON data and create new object with the specified keys in .
P.S Including code, so that it helps someone looking for reference.
Upvotes: 0
Reputation: 4179
PrimeNg provides a templating functionality which allows you to use your custom json.
<p-tree [value]="files">
<ng-template let-node pTemplate="default">
{{node.title}}
</ng-template>
</p-tree>
In above code title
is the json key, that I want to use to display in my tree.
Upvotes: 2