【发布时间】:2018-08-08 08:29:50
【问题描述】:
我正在开发由 JHipster 生成并使用 Angular 4.3 的应用程序。 我正在尝试使用tree component of PrimeNG
我正在尝试将对象数组转换为 TreeNode 数组,以便像树一样显示。
我的打字稿模型如下所示:
export class Continent implements BaseEntity {
constructor(
public id?: number,
public name?: string,
public countries?: Country[]
) { }
我关注了this subject,它描述了如何转换接口(但在我的情况下我有类)并且我有那些函数(哪里有错误):
private continentsToTreeNodes(continents: Continent[]) {
for (let cont of continents) {
this.continentsNodes.push(this.continentToTreeNode(cont));
}
}
private continentToTreeNode(cont: Continent): TreeNode {
return {
label: cont.name,
data: cont,
children: cont.countries.map(this.continentToTreeNode) // error at this line : cannot read property map of undefined
};
}
这些函数在我的组件初始化时执行:
export class MyComponent implements OnInit {
continents: Continent[];
continentsNodes: TreeNode[] = [];
ngOnInit() {
this.loadAll();
}
loadAll() {
this.continentService.query().subscribe(
(res: ResponseWrapper) => {
this.continents = res.json;
this.continentsToTreeNodes(this.continents);
},
(res: ResponseWrapper) => this.onError(res.json)
);
}
}
我的 JSON 看起来像这样:
[{
"id": 1,
"name": "Africa",
"countries": [{
"id": 8,
"name": "Cameroon",
"continentId": 1
}, {
... // other countries
],{
// other continents
...
有人知道为什么我的国家/地区出现此错误消息吗?
编辑: 我已经将日志放在continentToTreeNode 中,我可以看到问题出在递归函数上。 在第一个循环中,我拥有第一个大陆的所有国家,在第二个循环中崩溃,属性 cont.countries 未定义。
这怎么可能,我该如何解决?在我的 JSON 中,我有每个大陆的所有国家...
【问题讨论】:
-
cont.countries 是空的,看不到整个json输入,但是不完整。尝试在continentToTreeNode 中注销cont 以查看是哪一个。
标签: angular typescript jhipster primeng treenode