Mat Table 未在 ngOnIt 上显示数据,但在刷新后显示 [英] Mat Table is not displaying data on ngOnIt but after refresh its displaying

查看:16
本文介绍了Mat Table 未在 ngOnIt 上显示数据,但在刷新后显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Angular Material 与 Angular 一起使用.

我的表没有在 ngOnInit 生命周期钩子上显示数据,但在我刷新应用程序后它显示:

即使 ChangeDetectorRef 也不影响表格.

这是表格的模板:

<mat-table #table [dataSource]="dataSource"><ng-container matColumnDef="电话"><mat-h​​eader-cell *matHeaderCellDef>电话</mat-h​​eader-cell><mat-cell *matCellDef="let user">{{ user.phone }} </mat-cell></ng-容器><ng-container matColumnDef="LastName"><mat-h​​eader-cell *matHeaderCellDef>姓氏</mat-h​​eader-cell><mat-cell *matCellDef="let user" >{{ user.lastname}} </mat-cell></ng-容器><mat-h​​eader-row *matHeaderRowDef="displayedColumns"></mat-h​​eader-row><mat-row *matRowDef="let user; columns:displayedColumns;"></mat-row></mat-table><mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>

这是组件的文件:

import { ChangeDetectorRef } from '@angular/core';从 '@angular/material' 导入 { MatTableDataSource };从 './user.service' 导入 { UserService };导出类 UsersComponent 实现 OnInit {构造函数(私有引用:ChangeDetectorRef,私有 userService:UserService){}displayColumns = ['ID', 'FirstName', 'Phone', 'LastName'];数据源:MatTableDataSource<用户>;用户:用户[] = [];ngOnInit() {this.users= this.userService.getUserList();this.dataSource = new MatTableDataSource(this.users);this.ref.detectChanges();}

这是用于获取用户列表的 UserService 片段:

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/', 选项).map((数据:响应) => {返回 data.json() 作为 User[];}).toPromise().then(x => {this.userList = x;});返回 this.userList;}

解决方案

这个问题存在于 beta 版,但可以使用检测更改来解决.

在您的情况下,真正的问题是数据没有在 ngOnit 中分配,您需要使用 Observables 而不是 Promise 并在组件内订阅,如下更改您的服务,

 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());}

并在组件内部调用它,

 ngOnInit() {this.patientService.getPatients().subscribe((data) => {this.patients = 数据;console.log('#####patients inside ngonit', this.patients);this.dataSource = new MatTableDataSource(this.patients);});

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:

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;
    }

解决方案

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

这篇关于Mat Table 未在 ngOnIt 上显示数据,但在刷新后显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆