Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load Observable array property as Angular Material Table data source?

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?

like image 699
OreoFanatics Avatar asked Dec 20 '17 14:12

OreoFanatics


1 Answers

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>
...
like image 185
Preston Avatar answered Sep 21 '22 21:09

Preston