来自角材料的垫表不显示数据

时间:2019-07-17 16:39:20

标签: angular angular-material angular-material-table

我正在尝试在垫子表中显示一些来自api的数据。但是,即使我可以在控制台中看到数据,它也不会显示在mat表中。控制台不会显示与垫子表有关的任何错误,并且列标题正确显示。

我已经尝试使用async关键字在加载其余组件之前获取其余api数据。

这是我的组成部分

@Component({
  selector: 'admin-dashboard',
  templateUrl: './admin.component.html',
  providers: [HTTPService],
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit{
  showForm= false;
  buttonName= "Add User";
  users:User= [];
  tableColumns: string[] = ['name', 'email', 'company', 'phoneNumber', 'enabled', 'status'];

  constructor(private fb: FormBuilder, private http: HTTPService){};

  ngOnInit(){
      this.getUsers();
  }

  async getUsers()
  {
    var arr= await this.http.listUsers().toPromise();
    var i=0;
    while(arr[i])
    {
      this.users.push(arr[i]);
      i++;
    }
    console.log(this.users);

这是html模板


<table mat-table [dataSource]="users">
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef>Name</th>
    <td mat-cell *matCellDef="let user">{{user.name}}</td>
  </ng-container>
  <ng-container  matColumnDef="email">
    <th mat-header-cell *matHeaderCellDef>Email</th>
    <td mat-cell *matCellDef="let user">{{user.email}}</td>
  </ng-container>
  <ng-container  matColumnDef="company">
    <th mat-header-cell *matHeaderCellDef>Company</th>
    <td mat-cell *matCellDef="let user">{{user.company}}</td>
  </ng-container>
  <ng-container  matColumnDef="phoneNumber">
    <th mat-header-cell *matHeaderCellDef>Phone Number</th>
    <td mat-cell *matCellDef="let user">{{user.phoneNumber}}</td>
  </ng-container>
  <ng-container  matColumnDef="enabled">
    <th mat-header-cell *matHeaderCellDef>Enabled</th>
    <td mat-cell *matCellDef="let user">{{user.enabled}}</td>
  </ng-container>
  <ng-container  matColumnDef="status">
    <th mat-header-cell *matHeaderCellDef>Status</th>
    <td mat-cell *matCellDef="let user">{{user.status | lowercase}}</td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="tableColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: tableColumns"></tr>
</table>

如果需要更多信息,请告诉我,我是StackOverflow的新手

1 个答案:

答案 0 :(得分:1)

尝试如下使用dataSource设置mat-table中的new MatTableDataSource

TS

export class AdminComponent implements OnInit {

    dataSource;

    constructor(...){};

    ngOnInit() {

        this.getUsers();
    }

    async getUsers() {

        const arr = await this.http.listUsers().toPromise();
        let i = 0;
        while(arr[i]) {
            this.users.push(arr[i]);
            i++;
        }
        this.dataSource = new MatTableDataSource<any>(this.users);
    }
}

HTML

<table mat-table [dataSource]="dataSource">
...
</table>