我试图显示从本地 API 检索的简单数据,并将其存储在使用 mat-table
的数组中,但无济于事。我设法修复了它,但我对 Angular/Typescript/Programming 不太熟悉,我不知道为什么我的修复有效,有人可以帮助我理解为什么会这样吗?
pago.component.ts(修复前)
export class PagosComponent implements OnInit {
facturasElectricas: FacturaE[] = [];
displayedColumns: string[] = ['fecha', 'monto'];
...
ngOnInit() {
this.getFacturasElectricas();
}
getFacturasElectricas(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.pagoService.getFacturasElectricas().subscribe(facturas => {
facturas.forEach(f => {
if (f.factura.contrato === id && !f.factura.pagado) {
this.facturasElectricas.push(f);
}
});
});
}
}
pago.component.ts(修复后)
export class PagosComponent implements OnInit {
facturasElectricas: FacturaE[];
displayedColumns: string[] = ['fecha', 'monto'];
...
ngOnInit() {
this.getFacturasElectricas();
}
getFacturasElectricas(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.pagoService.getFacturasElectricas().subscribe(facturas => {
this.facturasElectricas = [];
facturas.forEach(f => {
if (f.factura.contrato === id && !f.factura.pagado) {
this.facturasElectricas.push(f);
}
});
});
}
}
我更改的唯一一行是 this.facturasElectricas = [];
,将其放置在 getFacturasElectricas()
方法中。
这是html部分 pago.component.html
<table *ngIf="facturasElectricas" mat-table #table [dataSource]="facturasElectricas">
<ng-container matColumnDef="fecha">
<th mat-header-cell *matHeaderCellDef> Fecha </th>
<td mat-cell *matCellDef="let element"> {{element.factura.fecha}} </td>
</ng-container>
<ng-container matColumnDef="monto">
<th mat-header-cell *matHeaderCellDef> Debe </th>
<td mat-cell *matCellDef="let element"> {{element.monto}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
最佳答案
我能想到的一件事是关于 Angular 的changeDetectionStrategy。
请参阅下面的链接,了解有关changeDetectionStrategy如何工作的全面信息:
具有异步数据源的示例代码(使用setTimeOut())
据我了解,mat-table 有一个OnPush changeDetectionStrategy,如 github 中的 Material 存储库所示:
简而言之,由于 dataSource 数组引用没有更改 mat-table 没有理由更新表行,并且在“修复”之后,通过使用 this.facturasElectricas = []
,您正在将新的数组对象分配给该属性,因此,mat-table 现在会收到 dataSource 现已更新的通知。
关于Angular mat-table 未显示数据,已修复,但不确定修复的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53925203/