Angular 4 ngx-treeview integration with json response

Prateek Chauhan picture Prateek Chauhan · Jul 25, 2017 · Viewed 9.6k times · Source

I'm currently new to angular 4 and using ngx-treeview(https://www.npmjs.com/package/ngx-treeview) to get the tree structure. Using static data able to bind view the tree.

But need to use the rest service to get the tree structure hence created a similar class TreeviewItem from ngx-treeview

public class TreeviewItem
{
    public string Text { get; set; }
    public int Value { get; set; }
    public bool Collapsed { get; set; }
    public TreeviewItem[] Children { get; set; }
} 

Here is json response which i'm getting

[{"text":"Core Fields","value":100,"collapsed":false,"children":null}]

Angular service:

return this.http.get(this.appHelpersSvc.apiAddress + 
"api/module/getStandardFields", { headers: httpHeaders })
.map((response:Response) => <TreeviewItem>response.json());

Angular Component

itemsList: TreeviewItem[]; 
this.moduleService.getStandardFields().subscribe(data => {this.itemsList = data;}); 

Doing so i'm getting

Uncaught TypeError: this.items[i].getCheckedItems is not a function
at TreeviewComponent.getCheckedItems (http://localhost:4001/main.bundle.js:42763:107)
at TreeviewComponent.raiseSelectedChange (http://localhost:4001/main.bundle.js:42745:34)
at TreeviewComponent.ngOnChanges (http://localhost:4001/main.bundle.js:42703:22)
at checkAndUpdateDirectiveInline (http://localhost:4001/vendor.dll.js:12160:19)
at checkAndUpdateNodeInline (http://localhost:4001/vendor.dll.js:13586:17)
at checkAndUpdateNode (http://localhost:4001/vendor.dll.js:13525:16)
at debugCheckAndUpdateNode (http://localhost:4001/vendor.dll.js:14228:59)
at debugCheckDirectivesFn (http://localhost:4001/vendor.dll.js:14169:13)

not able to understand what is going wrong. thanks for any help.

Answer

Leo Vo picture Leo Vo · Aug 20, 2017

I am author of this component. You need to map your JSON to list of TreeviewItem:

const list = items.forEach(item => new TreeviewItem(item));

and then binding list to component.