Angular 4 ngx-treeview integration with json response

Viewed 10952

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.

5 Answers
this.itemsList = data.map(value => {
            return new TreeviewItem({text: value.name, value: value.id, collapsed: true, children: filterChildren});
        });

use map method to iterate and create a new TreeView object and pass json object to the constructor.

My solution looks like this:

private generateTreeviewItemArray(categories: Category[]): TreeviewItem[] {
    let treeViewItems: TreeviewItem[] = [];
    for (let index = 0; index < categories.length; index++) {
      treeViewItems.push(new TreeviewItem({
          text: categories[index].name,
          value: categories[index].id
        } as TreeItem
      ));
    }
    return treeViewItems;
}

I create a new TreeviewItem using its constructor, where I create from the Category item a new Treeview object.

Related