Search code examples
angulartypeerrorangular-material-table

Material table sort courses type error when called onInit


I have a observable that i called on init. I also assign sort and pagnation to the datasource. Everythin seems to work. But I get an error.

Code

  dataSource = new MatTableDataSource(this.dataejers);

  @ViewChild(MatPaginator) paginator:any= MatPaginator;
  @ViewChild(MatSort) sort:any= MatSort;

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  ngOnInit(): void {
    this.stateService.startupData.subscribe((data: any) => {
      this.dataejers = data.dataejers;
      this.dataSource = new MatTableDataSource(this.dataejers);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
    })
  }

Error:

ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable

Solution

  • 1.First change:

    dataSource:MatTableDataSource<dataejers> = new MatTableDataSource<dataejers>();
    

    You are passing an undefined object to MatTableDataSource.

    2.Remove from ngOnInit (from the doc):

    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    

    3.Dont create a new MatTableDataSource:

    this.dataSource = new MatTableDataSource(this.dataejers);
    

    Assign data like this

    this.dataSource.data = data.dataejers;