2017-07-25 26 views
0

我目前是angular 4的新手,并使用ngx-treeview(https://www.npmjs.com/package/ngx-treeview)来获取树结构。使用静态数据能够绑定查看树。Angular 4 ngx-treeview与json响应的集成

但需要使用其他服务来获取树状结构因此产生从NGX-树状类似的类树型视图

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

这里是我得到

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

角JSON响应服务:

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

角度分量

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

这样做我得到

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) 

无法理解什么错误。 感谢您的任何帮助。

回答

0

什么是你的代码中的items?为什么你创建了TreeviewItem类,其中有三个属性?您是否尝试制作新的TreeviewItem类型并将其投射到json上?我不认为你需要它,因为已经有TreeviewItem

无论如何,请试试new TreeviewItem(json)(其中json是您从服务器获得的json字符串),而不是将其转换为TreeviewItem。但是在组件中,而不是在服务中。在使用中移除铸件。退还any返回的服务。顺便说一句,如果你演员演员,你应该做组件,而不是服务。应该更有效率,除非你在每个请求中只获取树视图。

我不是亲,但我认为你不应该使用演员只是因为你知道这是可能的。如果有创建对象的方法,你应该创建它。顺便说一下,有一个文档创建新项目的例子。

3

我是这个组件的作者。 你需要映射你的JSON列出树型视图的:

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

,然后绑定列表中的组成部分。

+0

嗨,利奥VO得到了解决,你做了一个很好的工具,可我知道我可以取消默认情况下所有的复选框。 – Karty

+0

您好,我如何设置复选框值,当我从数据库中检查项目值?我试图做到这一点:this.values = this.claims.map(x => x.checkedId);但没有结果。你可以帮我吗 ?谢谢 –

0

我做这样的

ngOnInit() { 
    this.service.getTreeViewdata() 
     .subscribe(items => 
        this.items = items, error => 
         this.errorMessage = error,() => 
          this.fillitemdata() 
    ); 
     debugger; 
} 

private fillitemdata(): void { this.items = this.getData(); } 

getData(): any[] { const itCategory = new TreeviewItem(this.items[0]); return [itCategory]; }