I have an Observable array property with the value fetched from Rest API.
Currently I am using ngFor to show the data in the standard html table.
Now I want to switch into Angular Material Table (MatTableDataSource). How do I load the [dataSource] with the data I have from the Observables?
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>
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With