【发布时间】:2018-06-21 21:23:39
【问题描述】:
在尝试为角度材料表设置数据源时陷入困境。
这就是我想要做的:
export class ServersTableDataSource extends DataSource<Server> {
data: Server[] = EXAMPLE_DATA;
constructor(private paginator: MatPaginator, private sort: MatSort, private serversService: ServersService) {
super();
this.data = this.serversService.getServers();
}
connect(): Observable<Server[]> {
const dataMutations = [
observableOf(this.data),
this.paginator.page,
this.sort.sortChange
];
// Set the paginators length
this.paginator.length = this.data.length;
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data]));
}));
}
export class ServersTableComponent implements OnInit {
constructor(private serversService: ServersService) { }
ngOnInit() {
this.dataSource = new ServersTableDataSource(this.paginator, this.sort, this.serversService);
this.serversService.serversChanges.subscribe(() => {
this.dataSource.data = this.serversService.getServers();
});
//done this way because for unknown reason if i return an observable,
//it doesn't pass a value. Anyway, this isn't relevant. The point is that this.dataSource.data is set.
}
在此示例中,尽管 connect 方法中有 observableOf(this.data),但 this.dataSource.data 更改不适用。
我能够使它工作的唯一方法是在每次更改时重新初始化数据源,这感觉不正确(表格非常频繁地从 websocket 数据更新)。
ngOnInit() {
this.dataSource = new ServersTableDataSource(this.paginator, this.sort, this.serversService);
this.serversService.serversChanges.subscribe(() => {
this.dataSource = new ServersTableDataSource(this.paginator, this.sort, this.serversService);
});
}
【问题讨论】:
标签: angular typescript