如何将Observable数组属性作为Angular Material Table数据源加载?

问题描述 投票:2回答:2

我有一个Observable数组属性,其值从Rest API获取。

目前我正在使用ngFor来显示标准html表中的数据。

现在我想切换到Angular Material Table(MatTableDataSource)。如何使用Observables中的数据加载[dataSource]?

angular angular-material observable
2个回答
3
投票

干得好。劈开这个。我在服务中有observable我调用了processor.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,
      );
  }

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.');
        }
      );
  }

我的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>
...

0
投票

您需要创建自定义DataSource或使用MatTableDataSource

here

© www.soinside.com 2019 - 2024. All rights reserved.