typescript Angular 控制台错误-错误类型错误:无法读取未定义的属性(正在阅读“data”)

cnh2zyt3  于 2023-01-21  发布在  TypeScript
关注(0)|答案(2)|浏览(214)

完整控制台错误:

ERROR TypeError: Cannot read properties of undefined (reading 'data")

at Oviewer Component 15A11Selected (oviewer.component.ts:97:37)

at OviewerComponent.checkbeaLabel (aviewer.component.ts:114:22)

at Oviewer Component th 26 Template (oviewer.component.html:79:68)

Oviewer.component.html

<div class="stable mat-elevation-z8">

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

<!-- Checkbox Column --> 
<ng-container matColumnDef="select">

<th mat-header-cell *matHeaderCellDef>

<mat-checkbox

(change)="$event? toggleAllRows(): null" color="primary"

[checked]="selection.hasValue() && isAllSelected()"

[indeterminate]-"selection.hasValue() && lisAllSelected()"

[aria-label]="checkboxLabel()"

</mat-checkbox>

Oviewer.component.ts

iSAllSelected() {

const numSelected =this.selection.selected.length;

const numRows =this.dataSource.data.length;

return numSelected === numRows;

/** Selects all rows if they are not all selected; otherwise clear selection.*/

toggleAllRows() {

if (this.isAllSelected())

{

this.selection.clear();

return;

}

this.selection.select(...this.dataSource.data);

}

/** The label for the checkbox on the passed row */

checkboxLabel(row?: any): string { if (!row) { return ${this.isAllSelected() ? 'deselect' : 'select') all';

}

我无法找到此问题的解决方案。有人能帮助我吗为什么我得到这个控制台错误?

1dkrff03

1dkrff031#

您必须查看错误消息:它说在oviewer.component.ts的第97行,您试图访问对象的'data'属性,但对象本身没有定义。
您没有提供行号,但我怀疑行号是:

this.selection.select(...this.dataSource.data);

datasource对象是数据的 Package 器,所以要使用它,你必须首先初始化它(可能在类中,或者在构造函数中,例如dataSource = new DataSource([])),然后数据源就可以修改了。

slhcrj9b

slhcrj9b2#

如果在访问“数据”之前进行验证,将有所帮助。示例:

const numRows = this.dataSource && this.dataSource.data ? this.dataSource.data.length : [];

相关问题