I'm working on an application generated by JHipster and using Angular 4.3. I'm trying to use the tree component of PrimeNG
I'm trying to convert an array of objects into an array of TreeNode, in order to be displayed like a tree.
My typescript model looks like this :
export class Continent implements BaseEntity {
constructor(
public id?: number,
public name?: string,
public countries?: Country[]
) { }
I've followed this subject which describes how to convert interfaces (but in my case I have classes) and I've thoses functions (where there is the error):
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
};
}
Those functions are executed at the initialization of my component :
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)
);
}
}
My JSON looks like this :
[{
"id": 1,
"name": "Africa",
"countries": [{
"id": 8,
"name": "Cameroon",
"continentId": 1
}, {
... // other countries
],{
// other continents
...
Does anyone know why I have this error message with my countries ?
EDIT : I've put logs in continentToTreeNode, and I can see that it's the recursive function the problem. At the first loop I have all the countries of the first Continent, and it crashed at the second loop, the attribute cont.countries is undefined.
How is it possible and how can I fix it ? In my JSON I have all the countries of each continent...