问题
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() {}
}
and this is my table
<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>
and
<mat-row *matRowDef="let row| async"; columns: displayedColumns;">
Is what I'm trying to do possible in any way?
回答1:
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);
}
来源:https://stackoverflow.com/questions/51808215/populating-mattables-with-promises-asynchronous-rows