How to load Observable array property as Angular Material Table data source?
Here you go. Hack away at this. I have the observable in a service I call processor.service and it uses the same code is used to populate all my tables. The vars are in the component and are passed through to the service:
component
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,
);
}
processor.service
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.');
}
);
}
My html isn't ngFor but should be useful. The results create a long table that requires pagination and probably accomplishes what you want.
<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>
...
Just [dataSource]="Observable<ReadOnlyArray>"
works. The commit feat(table): allow data input to be array, stream (#9489) seems at Angular 5.2 . For now, allowed types are DataSource<T> | Observable<ReadonlyArray<T> | T[]> | ReadonlyArray<T> | T[]
.