您遇到的问题有两个部分:
HTML 示例:
<ng-container *ngIf="data$ | async as data; else loading">
<table>
<thead>
<th>ID</th>
<th>Code</th>
<th>Buttons</th>
</thead>
<tbody>
<tr *ngFor="let item of data">
<td>{{ item.id }}</td>
<td>{{ item.code }}</td>
<td>
@for (idx of buttonCount; track idx; let index = $index) {
<button>{{ idx }}</button>
}
</td>
</tr>
</tbody>
</table>
</ng-container>
<ng-template #loading><mat-spinner></mat-spinner></ng-template>
更新了服务以更好地模拟异步数据(也可以作为 Observable 共享):
async fetchData(): Promise<ApiModel[]> {
let result: ApiModel[] = [];
for (let i = 1; i <= this.cnt; i++) {
result.push({ id: i, code: `item_${i}` });
}
return new Promise((resolve, reject) => {
setTimeout(() => resolve(result), Math.random() * 5000);
});
}
结果是立即交换选项卡,在加载数据时显示一个微调器图标: