我是 Angular 19 的 RxResource API 新手。问题是材质表不显示从 rxResource 加载的数据(但我可以使用一个小技巧来显示它。这根本没有意义)我就是这么做的)。 这是我的代码: 我的模板:
<mat-table #table [dataSource]="dataSource" matSort class="mat-elevation-z8" multiTemplateDataRows>
<ng-container matColumnDef="webTubeLink">
<mat-header-cell *matHeaderCellDef mat-sort-header>Tube Link</mat-header-cell>
<mat-cell *matCellDef="let row">{{row.webTubeLink}}</mat-cell>
</ng-container>
<ng-container matColumnDef="videoId">
<mat-header-cell *matHeaderCellDef mat-sort-header>Video Id</mat-header-cell>
<mat-cell *matCellDef="let row">{{row.videoId}}</mat-cell>
</ng-container>
<ng-container matColumnDef="title">
<mat-header-cell *matHeaderCellDef mat-sort-header>Title</mat-header-cell>
<mat-cell *matCellDef="let row">{{row.webTubeTitle}}</mat-cell>
</ng-container>
<ng-container matColumnDef="actions">
<mat-header-cell *matHeaderCellDef>
<span><i class='bi bi-plus-circle' (click)="addNew()"></i> Add</span>
</mat-header-cell>
<mat-cell *matCellDef="let row; let i=index;">
<span class='bi bi-pencil-fill' (click)="startEdit(row)" style="margin-right: 1rem"> Edit</span>
<span class='bi bi-trash-fill' (click)="deleteItem(row)"> Delete</span>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
</div>
这是我的代码组件:
tubeRecordsRS = rxResource<any[], any>({
loader: () => this.http.get<any[]>('/Tube/Gettubes')
});
tubeRecords = computed(() => {
this.dataSource = new MatTableDataSource(this.tubeRecordsRS.value());
this.dataSource.paginator = this.paginator;
return this.tubeRecordsRS.value();
})
这是我通过将以下代码添加到模板来显示材料表中的数据的修复
<p style="display: none">{{ tubeRecords() | json }}</p>
使用代码,应用程序可以正常工作。
为什么? 我做错了什么? 还有其他方法可以解决这个问题吗?
正如您在 docs 中所读到的那样,仅当实际读取信号值时才会执行
computed
函数内部的计算,而您的应用程序中并非如此,除非添加了包含读取的信号的段落。
effect
在这里会是更好的选择:
export class YourComponent {
tubeRecordsRS = rxResource<any[], any>({
loader: () => this.http.get<any[]>('/Tube/Gettubes')
});
dataSource = new MatTableDataSource();
constructor() {
effect(() => {
this.dataSource.data = this.tubeRecordsRS.value();
});
}
}