【发布时间】:2018-05-30 04:03:43
【问题描述】:
我正在使用 Angular 和 SpringMVC 框架构建一个 webapp。 我正在尝试加载用户列表(在代码中名为“consulenti”)。来自后端的 http 请求一切正常但是当我尝试在前端部分使用 TypeScript 处理数据时,我不断收到如下错误:
无法设置未定义的属性“headerRow” 在 TablesComponent.ngOnInit (webpack-internal:///./src/app/tables/tables.component.ts:27
无法读取未定义的属性“headerRow”
无法读取未定义的属性“push”
其他属性以此类推。
我正在尝试在表格中显示数据,使用免费的 Angular 仪表板客户端作为模板。
下面是代码。
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>
非常感谢您!
更新
当从 http 请求检索数据到数组“consulenti”时,它现在卡在订阅中。从调试器观察复制操作进展顺利,但订阅结束后数组再次变为空。
代码
this.dataService.getConsulenti().subscribe((data: Consulente[]) => {
this.consulenti = data;
}); // stuck after this.
【问题讨论】:
-
公共顾问数据:表格数据; -> undefined this.consulentiData.headerRow = this.undefined.headerRow -> 不能设置属性'headerRow' of undefined 就像Prachi说你需要先初始化你的字段。
标签: angular typescript