Объект - это массив при заполнении HTML-таблицы, но не при итерации в машинописи - PullRequest
0 голосов
/ 19 января 2019

У меня есть внутренняя база данных, которая обслуживает записи студентов в виде файлов 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? Как мне заставить его обрабатывать объект как массив?

1 Ответ

0 голосов
/ 19 января 2019

очевидно, нет 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>

Редактировать: вы подписываетесь на асинхронный метод с подпиской, но выпытаемся сделать назначения после подписки.из-за этого ваша функция не ждет окончания подписки.Решение вашей проблемы:

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
});
...