title: Angular material data table from rest api
body: <p>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.</p>
  <pre><code>export class OrdersDetailsComponent implements AfterViewInit, OnInit {
    @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
    @ViewChild(MatSort, { static: false }) sort: MatSort;
    @ViewChild(MatTable, { static: false }) table: MatTable&lt;OrdersDetailsItem&gt;;
  
    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) =&gt; {
        this.dataSource.data = data
        console.log(data)
        return data
      })
    }
  
    ngAfterViewInit() {
         this.table.dataSource = this.dataSource;
  
    }
  }
  
  </code></pre>
  <p>my api</p>
  <pre><code>  getOrders() {
      return this.http.get(environment.apiUrl + 'admin/getAllOrders')
    }
  </code></pre>
  <p>my html</p>
  <pre><code>&lt;div class=&quot;mat-elevation-z8&quot;&gt;
    &lt;table mat-table #table [dataSource]=&quot;dataSource&quot; class=&quot;full-width-table&quot; matSort aria-label=&quot;Elements&quot;&gt;
      &lt;!-- Id Column --&gt;
      &lt;ng-container matColumnDef=&quot;OrderId&quot;&gt;
        &lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt;Id&lt;/th&gt;
        &lt;td mat-cell *matCellDef=&quot;let row&quot;&gt;{{row.OrderId}}&lt;/td&gt;
      &lt;/ng-container&gt;
  
      &lt;!-- Name Column --&gt;
      &lt;ng-container matColumnDef=&quot;OrderNumber&quot;&gt;
        &lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt;Order number&lt;/th&gt;
        &lt;td mat-cell *matCellDef=&quot;let row&quot;&gt;{{row.OrderNumber}}&lt;/td&gt;
      &lt;/ng-container&gt;
  
      &lt;tr mat-header-row *matHeaderRowDef=&quot;displayedColumns&quot;&gt;&lt;/tr&gt;
      &lt;tr mat-row *matRowDef=&quot;let row; columns: displayedColumns;&quot;&gt;&lt;/tr&gt;
    &lt;/table&gt;
  
    &lt;mat-paginator #paginator [length]=&quot;dataSource?.data.length&quot; [pageIndex]=&quot;0&quot; [pageSize]=&quot;50&quot;
      [pageSizeOptions]=&quot;[25, 50, 100, 250]&quot;&gt;
    &lt;/mat-paginator&gt;
  &lt;/div&gt;
  </code></pre>