Mat Table is not displaying data on ngOnIt but aft

2019-04-13 17:26发布

I'm using Angular Material with Angular.

My table does not display data on the ngOnInit lifecycle hook, but after I refresh the app it displays: Values are in my array but not displaying in the table

Even ChangeDetectorRef doesn't affect the table.

Here is the template for the table:

<div class="example-container mat-elevation-z8">
<mat-table #table [dataSource]="dataSource"> 
    <ng-container matColumnDef="Phone">
        <mat-header-cell *matHeaderCellDef> Phone </mat-header-cell>
        <mat-cell *matCellDef="let user"> {{ user.phone }} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="LastName">
        <mat-header-cell *matHeaderCellDef> LastName </mat-header-cell>
        <mat-cell   *matCellDef="let user" > {{ user.lastname}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let user; columns: displayedColumns;"></mat-row>
    </mat-table>
    <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>

And here's the component's file:

import { ChangeDetectorRef } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { UserService } from './user.service';

export class UsersComponent implements OnInit {
    constructor(private ref: ChangeDetectorRef, private userService: UserService){}
    displayedColumns = ['ID', 'FirstName', 'Phone', 'LastName'];
    dataSource: MatTableDataSource<User>;
    users: User[] = [];
    ngOnInit() {
        this.users= this.userService.getUserList();
        this.dataSource = new MatTableDataSource(this.users);
        this.ref.detectChanges();
    }

Here is a snippet of UserService for getting a user list:

getUserList() {
    const headers = new Headers({'Content-Type': 'application/json', 'Authorization': 'Bearer ' + this.authenticationService.token});
    const options = new RequestOptions({ headers: headers });
    this.http.get('/api/getallusers/', options)
     .map((data: Response) => {
         return data.json() as User[];
      }).toPromise().then(x => {
         this.userList = x;
      });
      return this.userList;
    }

2条回答
2楼-- · 2019-04-13 17:46

Here is the answer:

ngAfterViewInit() {
  Your code here.
  }
查看更多
ら.Afraid
3楼-- · 2019-04-13 17:48

This issue was there with the beta version though and that could be resolved using detect changes.

In your case , the real issue is data is not getting assigned in ngOnit, you need to use Observables instead of Promise and subscribe inside the component, Change your service as follows,

 getPatients() {
    const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + this.authenticationService.token });
    const options = new RequestOptions({ headers: headers });
    return this.http.get('/api/getallpatients/', options)
      .map((response: Response) => response.json());
  }

and call it inside the component as,

 ngOnInit() {
    this.patientService.getPatients().subscribe((data) => {
      this.patients = data;
      console.log('#####patients inside ngonit', this.patients);
      this.dataSource = new MatTableDataSource(this.patients);
    });
查看更多
登录 后发表回答