我正在研究由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中,我拥有各大洲的所有国家......
我已经解决了我的(愚蠢)问题,我正在迭代一个需要大陆的功能,而我正试图转换国家。改变国家的另一个功能是可以的:
private continentsToTreeNodes(continents: Continent[]) {
for (let cont of continents) {
this.continentsNodes.push(this.continentToTreeNode(cont));
}
}
private continentToTreeNode(cont: Continent): TreeNode {
let countiesTreeNodes: TreeNode[] = [];
if (cont.countries !== undefined) {
for (let c of cont.countries) {
countriesTreeNodes.push(this.paysToTreeNode(c));
}
}
return {
label: cont.nom,
data: cont,
children: countriesTreeNodes
};
}
private countryToTreeNode(country: Country) : TreeNode {
return {
label: country.nom,
data: country
}
}