Home:ALL Converter>Angular 6 Material table datasource

Angular 6 Material table datasource

Ask Time:2018-06-22T05:23:39         Author:user1935987

Json Formatter

get quite stuck trying to set the datasource for the angular material table.

this is what i'm trying to do:

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 example, despite that there is observableOf(this.data) in connect method, the this.dataSource.data changes do not apply.

The only way i was able to make it work is to re-initialize datasource on each change, which doesn't feel right (table is updated from websocket data very frequently).

  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);
    });
  }

Author:user1935987,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50977621/angular-6-material-table-datasource
yy