【发布时间】:2018-06-19 14:07:11
【问题描述】:
我将 Angular 材质与 Angular 一起使用。
我的表没有在 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 的 sn-p,用于获取用户列表:
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;
}
【问题讨论】:
-
使用
ngAfterViewInit -
@Und3rTow 与 ngafterviewInit 的结果相同
-
我只用 observables 做到了这一点,但我认为你的承诺会在 ngOnInit 完成后重新开始。并在此阶段返回一个空列表。您也可以尝试使用 markForCheck() 而不是 detectChanges()
标签: typescript angular-material angular-material2 angular5