Mahmoud Nafea
Mahmoud Nafea

Reputation: 117

Angular material data table from rest api

I'm new to Angular and angular material.I can't bind and display my data from the http service into the table. when I console the data I get it after the page is loaded. sometimes I get error of undefined. Please find my code below as I use it.

export class OrdersDetailsComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: false }) sort: MatSort;
  @ViewChild(MatTable, { static: false }) table: MatTable<OrdersDetailsItem>;

  dataSource: OrdersDetailsDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['OrderId', 'OrderNumber'];

  constructor(
    private apiService: OrdersDetailsService
  ) { }

  ngOnInit() {
     this.dataSource = new OrdersDetailsDataSource();
    this.getAllOrders()
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;

  }
  getAllOrders() {
    this.apiService.getOrders().subscribe((data: any) => {
      this.dataSource.data = data
      console.log(data)
      return data
    })
  }

  ngAfterViewInit() {
       this.table.dataSource = this.dataSource;

  }
}

my api

  getOrders() {
    return this.http.get(environment.apiUrl + 'admin/getAllOrders')
  }

my html

<div class="mat-elevation-z8">
  <table mat-table #table [dataSource]="dataSource" class="full-width-table" matSort aria-label="Elements">
    <!-- Id Column -->
    <ng-container matColumnDef="OrderId">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
      <td mat-cell *matCellDef="let row">{{row.OrderId}}</td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="OrderNumber">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Order number</th>
      <td mat-cell *matCellDef="let row">{{row.OrderNumber}}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

  <mat-paginator #paginator [length]="dataSource?.data.length" [pageIndex]="0" [pageSize]="50"
    [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>
</div>

Upvotes: 1

Views: 7571

Answers (1)

Hansaka Sandaruwan
Hansaka Sandaruwan

Reputation: 521

Try like below. create the dataSource object after you get the data from the api.

dataSource = new MatTableDataSource < OrdersDetailsDataSource > (null);

ngOnInit() {
  this.getAllOrders()
}

getAllOrders() {
    this.apiService.getOrders().subscribe((data: any) => {
      this.dataSource = new MatTableDataSource < OrdersDetailsDataSource > (data); //pass the array you want in the table
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
      return data
    })

Upvotes: 1

Related Questions