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

Angular PrimeNg TreeNode : convert class into TreeNode, cannot read property map of undefined

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

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

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

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

我已经按照 描述了如何转换接口(但在我的例子中我有 类)并且我有那些函数(有错误的地方):

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