Angular PrimeNg TreeNode:将类转换为TreeNode,无法读取未定义的属性映射

Nea*_*sis 1 treenode typescript jhipster primeng angular

我正在开发一个由 JHipster 生成并使用 Angular 4.3 的应用程序。我正在尝试使用PrimeNG 的树组件

我正在尝试将对象数组转换为 TreeNode 数组,以便像树一样显示。

我的打字稿模型如下所示:

export class Continent implements BaseEntity {
    constructor(
        public id?: number,
        public name?: string,
        public countries?: Country[]
) { }
Run Code Online (Sandbox Code Playgroud)

我遵循了这个主题,它描述了如何转换接口(但在我的例子中我有类)并且我有这些函数(哪里有错误):

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
    };
}
Run Code Online (Sandbox Code Playgroud)

这些函数在我的组件初始化时执行:

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)
        );
    }

}
Run Code Online (Sandbox Code Playgroud)

我的 JSON 如下所示:

[{
"id": 1,
"name": "Africa",
"countries": [{
        "id": 8,
        "name": "Cameroon",
        "continentId": 1
        }, {
        ... // other countries
],{
// other continents
...
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么我的国家/地区会出现此错误消息?

编辑: 我已将日志放入 ContinentalToTreeNode 中,我可以看到这是递归函数的问题。在第一个循环中,我拥有第一个大陆的所有国家,在第二个循环中崩溃,属性 cont.countries 未定义。

这怎么可能以及我该如何解决它?在我的 JSON 中,我有每个大陆的所有国家/地区...

Nea*_*sis 5

我已经解决了我的(愚蠢的)问题,我正在迭代一个需要大陆的函数,并且我正在尝试转换国家/地区。可以使用另一个改变国家的功能:

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
    }
}
Run Code Online (Sandbox Code Playgroud)