用承诺(异步行)填充 MatTables [英] Populating MatTables with promises (asynchronous rows)
问题描述
我正在尝试在 MatTable 中显示一组对象.我有一个包含每个对象 URL 的列表,所以我想异步填充行(我可以预先拥有所有空行,然后在加载数据时填写数据)所以,这是我的数据源
I'm trying to display a collection of objects in a MatTable. I have a list with each object's URL, so I want to populate the rows asynchronously (I'm ok with having all the empty rows upfront, and then fill in the data as I load it) So, this is my data source
export class TableDataSource extends DataSource<Promise<any>> {
private _items: Promise<any>[];
constructor(private loader: LoaderService, private collection: ObjectMember) {
super();
}
connect(): Observable<Promise<any>[]> {
if (!this._items) {
//aggregates each Promise<any> into an array.
this._items = this.collection.value.map(x => this.mm.load(ObjectRepr, x.href));
}
return Observable.of(this._items);
}
disconnect() {}
}
这是我的桌子
<mat-table #table [dataSource]="CollectionSource" class="mat-elevation-z8" sort>
<ng-container matColumnDef="Name">
<mat-header-cell *matHeaderCellDef> Name</mat-header-cell>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
这显示了正确的行数,但没有填充.承诺没有得到解决.
This is showing the right number of rows, but they are not populated. The Promises are not getting resolved.
我尝试了以下方法,但在这两种情况下我都遇到了编译错误:
I've tried the following things but in both cases I got compile errors:
<td mat-cell *matCellDef="let element | async"> {{element.name}} </td>
和
<mat-row *matRowDef="let row| async"; columns: displayedColumns;">
我正在努力做的事情以任何方式可行吗?
Is what I'm trying to do possible in any way?
推荐答案
需要使用Observable.forkjoin()来处理for循环中的observable.
You need to use Observable.forkjoin() to handle the observable in for loop.
connect(): Observable<Promise<any>[]> {
const observable = [];
if (!this._items) {
//aggregates each Promise<any> into an array.
this.collection.value.forEach(x => {
const obs = this.mm.load(ObjectRepr, x.href));
observable.push(obs);
});
}
return Observable.forkjoin(observable);
}
这篇关于用承诺(异步行)填充 MatTables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!