I'm building a webapp using Angular and the SpringMVC Framework. I'm trying to load a list of users (named "consulenti" in the code). Everthing with the http request from the backend is fine But when I try to handle the data using TypeScript in the frontend part I keep getting errors like this:
Cannot set property 'headerRow' of undefined at TablesComponent.ngOnInit (webpack-internal:///./src/app/tables/tables.component.ts:27
Cannot read property 'headerRow' of undefined
Cannot read property 'push' of undefined
and so on with the other properties.
I'm trying to show the data in a table, using a free angular dashboard client as a template.
Here below is the code.
tables.component.ts
export class TablesComponent implements OnInit {
public consulenti: Consulente[];
public consulentiData: TableData;
private rows: number;
private cols: number;
constructor(private dataService: DataService) {} // Service injection
setRowData() {
if (this.rows != undefined && this.cols != undefined) {
for (let i = 0; i < this.cols; i++) this.consulentiData.dataRows[i] = this.consulenti[i].stringify();
}
// else error
}
ngOnInit() {
this.consulentiData.headerRow = ['Id', 'Nome', 'Cognome', 'E-mail', 'Scadenza contratto'];
this.dataService.getConsulenti().subscribe(data => {
for (let i = 0; i < data.length; i++) this.consulenti.push(data[i]);
});
this.rows = this.consulenti.length;
this.cols = this.consulenti[0].stringifyFields;
this.consulentiData.headerRow = ['Id', 'Nome', 'Cognome', 'E-mail', 'Scadenza contratto'];
this.setRowData();
}
tables.template.html
<div class="content table-responsive table-full-width">
<table class="table table-hover table-striped">
<thead>
<tr>
<th *ngFor="let cell of consulentiData.headerRow">{{ cell }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of consulentiData.dataRows">
<td *ngFor="let cell of row">{{cell}}</td>
</tr>
</tbody>
</table>
</div>
Thank you very much in advance!
UPDATE
It now gets stuck in the subscription, when retrieving data from the http request to the array "consulenti". Watching from debugger the copy operation goes well but then the array become again empty after the subscription ends.
Code
this.dataService.getConsulenti().subscribe((data: Consulente[]) => {
this.consulenti = data;
}); // stuck after this.