I'm encountering difficulty setting the datasource for the Angular Material table.
Here is what I am trying to accomplish:
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.
}
In this scenario, although there is observableOf(this.data)
in the connect
method, changes to this.dataSource.data
do not take effect.
The only solution I found was to reinitialize the datasource each time, which seems inefficient considering the table is frequently updated with websocket data.
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);
});
}