我正在使用Angular的Angular Material。
我的表格不显示ngOnInit
生命周期挂钩上的数据,但在刷新应用后,它会显示:
即使ChangeDetectorRef
也不会影响表格。
以下是表格的模板:
<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>
这是组件的文件:
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();
}
以下是获取用户列表的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/', options)
.map((data: Response) => {
return data.json() as User[];
}).toPromise().then(x => {
this.userList = x;
});
return this.userList;
}
答案 0 :(得分:2)
此问题与 beta version
有关,可以使用 detect changes.
在您的情况下,真正的问题是数据没有在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 = data;
console.log('#####patients inside ngonit', this.patients);
this.dataSource = new MatTableDataSource(this.patients);
});
答案 1 :(得分:0)
以下是答案:
ngAfterViewInit() {
Your code here.
}