gpt4 book ai didi

Angular mat-table 没有显示数据,已修复但不确定修复的原因

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:26 24 4
gpt4 key购买 nike

我试图显示从我使用 mat-table 存储在数组中的本地 API 检索的简单数据,但无济于事。我设法修复了它,但总体上我是 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>

Output before fix

Output after fix

最佳答案

我能想到的一件事是关于 Angular 的 changeDetectionStrategy。

有关 changeDetectionStrategy 如何工作的全面信息,请参阅下面的链接:

带有异步数据源的示例代码(使用setTimeOut())

在我的理解中,ma​​t-table 有一个 OnPush changeDetectionStrategy,如 github 的 material repo 所示:

简而言之,由于数据源数组引用没有改变,ma​​t-table 没有理由更新表格行,在“修复” 之后,通过使用 this.facturasElectricas = [],您正在为该属性分配新的数组对象,因此,ma​​t-table 现在收到通知,dataSource 现已更新。

关于Angular mat-table 没有显示数据,已修复但不确定修复的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53925203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com