Ore*_*ics 5 observable angular-material angular
我有一个Observable数组属性,其值是从Rest API获取的。
目前,我正在使用ngFor在标准html表中显示数据。
现在,我想切换到Angular Material Table(MatTableDataSource)。如何使用来自Observables的数据加载[dataSource]?
干得好。别客气了。我在可称为service.service的服务中具有可观察性,它使用相同的代码来填充所有表。变量位于组件中,并传递给服务:
零件
private dbTable = 'members'; // The table name where the data is.
private dataSource = new MatTableDataSource();
private displayedColumns = [
'firstName',
'lastName',
...]
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
}
// ------ GET ALL -----
private getAllRecords() {
return this.mainProcessorService.getAllRecords(
this.dbTable,
this.dataSource,
this.paginator,
);
}
Run Code Online (Sandbox Code Playgroud)
处理器服务
getAllRecords(dbTable, dataSource, paginator) {
dataSource.paginator = paginator;
// Populate the Material2 DataTable.
Observable.merge(paginator.page)
.startWith(null) // Delete this and no data is downloaded.
.switchMap(() => {
return this.httpService.getRecords(dbTable,
paginator.pageIndex);
})
.map(data => data.resource) // Get data objects in the Postgres resource JSON object through model.
.subscribe(data => {
this.dataLength = data.length;
dataSource.data = data;
},
(err: HttpErrorResponse) => {
console.log(err.error);
console.log(err.message);
this.messagesService.openDialog('Error', 'Database not available.');
}
);
}
Run Code Online (Sandbox Code Playgroud)
我的html不是ngFor,但应该有用。结果将创建一个需要分页的长表,并可能完成您想要的操作。
<mat-table #table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="firstName">
<mat-header-cell fxFlex="10%" *matHeaderCellDef> First Name </mat-header-cell>
<mat-cell fxFlex="10%" *matCellDef="let row"> {{row.first_name}} </mat-cell>
</ng-container>
<ng-container matColumnDef="lastName">
<mat-header-cell fxFlex="10%" *matHeaderCellDef mat-sort-header> Last Name </mat-header-cell>
<mat-cell fxFlex="10%" *matCellDef="let row"> {{row.last_name}} </mat-cell>
</ng-container>
...
Run Code Online (Sandbox Code Playgroud)
就[dataSource]="Observable<ReadOnlyArray>"
可以了。提交壮举(表):允许数据输入为数组,流(#9489)似乎在 Angular 5.2 中。目前,允许的类型是DataSource<T> | Observable<ReadonlyArray<T> | T[]> | ReadonlyArray<T> | T[]
.
归档时间: |
|
查看次数: |
8384 次 |
最近记录: |