我有一个后端数据库,该数据库将学生记录作为JSON文件提供。然后将这些对象填充到PrimeNG表中以进行显示和选择。
student.component.html
<p-table class="table" [columns]="cols" [value]="searchResults">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData>
<tr [pSelectableRow]="rowData" class="tr-click" (click)="getSelected(rowData)">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
</p-table>
但是,当我尝试读取或遍历TypeScript中的学生记录时,出现“ TypeError:无法读取未定义的属性XXX”。
student.component.ts
export class StudentComponent implements OnInit {
searchResults: Student[];
cols: any[];
constructor(private router: Router, private studentService: StudentService, private http: HttpClient) {
}
ngOnInit(): void {
this.studentService.getStudents().subscribe(data => {
this.searchResults = data;
});
// table columns
this.cols = [
{ field: 'studentId', header: 'Student ID'},
{ field: 'name', header: 'Name'},
{ field: 'dob', header: 'Date of Birth'},
{ field: 'status', header: 'Status'}
];
// tested the object with these
alert('1: ' + JSON.stringify(this.searchResults)); // undefined
alert('2: ' + this.searchResults); // undefined
alert('3: ' + this.searchResults.toString); // undefined
}
// This is what I am trying to accomplish
getSelected(selected: Student) {
for (const result of this.searchResults) {
if (selected.studentID === result.studentID) {
// do some other stuff
}
}
}
那么为什么PrimeNG表能够用对象填充表,但是我不能在TypeScript中对其进行迭代?如何获得将对象视为数组的方法?
答案 0 :(得分:1)
显然,您的columns
文件中没有ts
声明
<tr [pSelectableRow]="rowData" class="tr-click" (click)="getSelected(rowData)">
<td *ngFor="let col of columns">
{{car[col.field]}}
</td>
</tr>
到
<tr [pSelectableRow]="rowData" class="tr-click" (click)="getSelected(rowData)">
<td *ngFor="let col of cols">
{{car[col.field]}}
</td>
</tr>
编辑:您正在使用subscribe订阅异步方法,但是您尝试在订阅后进行分配。因此,您的功能不会等待订阅完成。您的问题的解决方案是:
this.studentService.getStudents().subscribe(data => {
this.searchResults = data;
// table columns
this.cols = [
{ field: 'studentId', header: 'Student ID'},
{ field: 'name', header: 'Name'},
{ field: 'dob', header: 'Date of Birth'},
{ field: 'status', header: 'Status'}
];
// tested the object with these
alert('1: ' + JSON.stringify(this.searchResults)); // undefined
alert('2: ' + this.searchResults); // undefined
alert('3: ' + this.searchResults.toString); // undefined
});