【发布时间】:2019-03-31 12:02:58
【问题描述】:
我有一个来自端点的数据并将其放入 MatTableDataSource。我能够让它为 MatSort 和 MatPaginator 工作,但需要使用 setTimeOut,这似乎不是正确的方法。如果我删除它,它会抱怨“无法读取未定义排序的属性”,我认为这是因为它尚未初始化。
我也试过了:
- 将其移至 afterviewinit,但数据是在之后加载的 afterviewinit 被调用所以它仍然不起作用
- 在 this.datasource = 之后使用 this.changeDetectorRef.detectChanges() 新...也不起作用
这是我当前的代码(正在运行,但使用 settimeout)
<div *ngIf="!isLoading">
<div *ngFor="let record of renderedData | async" matSort>
// ... some html to show the 'record'
<mat-paginator #paginator
[pageSizeOptions]="[5, 10, 20]">
</mat-paginator>
</div>
组件
export class ResultsComponent implements OnInit, OnDestroy, AfterViewInit {
dataSource: MatTableDataSource<any> = new MatTableDataSource();
renderedData: Observable<any>;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor(some service) {}
ngOnInit() {
const accountId = someOtherService.getAccountId();
this.someService.getData(accountId)
.subscribe((myData) => {
this.dataSource = new MatTableDataSource(myData);
// it won't work properly if it is not wrapped in timeout
setTimeout(() => {
this.dataSource.paginator = this.paginator;
this.sort.sort(<MatSortable>({id: 'created_on', start: 'desc'}));
this.dataSource.sort = this.sort;
});
this.renderedData = this.dataSource.connect();
}
});
}
ngAfterViewInit() {
}
ngOnDestroy(): void {
if (this.dataSource) { this.dataSource.disconnect(); }
}
}
上面的代码对我有用,我只是在寻找不使用 settimeout 的正确方法。
【问题讨论】:
-
通过订阅创建 MatTableDataSource 时我也必须这样做。期待看到这个问题的答案。
-
更好的解决方法可能是在
this.dataSource = ...之后调用ChangeDetectorRef.detecChanges(),而不是使用setTimeout。 -
@ConnorsFan 试过了,它给了我“Cannot read property 'sort' of undefined at SafeSubscriber._next”。我在构造函数中添加private changeDetectorRef:ChangeDetectorRef,然后在this.datasource = new Mat下面... this.changeDetectorRef.detectChanges();
-
@ConnorsFan,
detectChanges对当前视图和所有孩子进行全面检查,这是一种非常昂贵的方式,与这种方式相比,空的setTimeout看起来并不邪恶,恕我直言
标签: javascript angular sorting pagination angular-material