首页 > 解决方案 > 如何使用 Angular 8 使用材料表显示数据源

问题描述

我正在使用 Angular 材料表,但我没有遇到如何在我的屏幕上显示数据源。这是我正在使用的代码:

我有 eventto-table.component.ts 从服务器请求数据:

  dataSource: EventoTableDataSource;

  eventos: Array<any> = new Array();

  constructor(private eventosService: EventosService) { }


  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['pais', 'regiao', 'sensor', 'timestampDt', 'valor', 'status'];

  ngOnInit() {
    this.listarEventos();
    this.dataSource = new EventoTableDataSource();
    console.log('dataSource', this.dataSource);
  }

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

  listarEventos() {
    this.eventosService.listarEventos().subscribe(eventos => {
      this.dataSource.data = eventos;
      return eventos;
    });
  }
}

在这里我不知道如何使用 dataSource 在我的视图中显示:

事件表数据源.ts

// TODO: replace this with real data from your application
const EVENTOS: EventoTableItem[] = [{
  id: 1,
  pais: 'Brasil',
  regiao: 'Sudeste',
  sensor: '001',
  valor: 3000,
  status: 'Processado',
  timestampDt: '2019-06-19T00:00:00Z'
  }];

export class EventoTableDataSource extends DataSource<EventoTableItem> {
  data: EventoTableItem[] = EVENTOS;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }

  connect(): Observable<EventoTableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  disconnect() {}

  ...
}

这是我设置表格可视化的方式:

<table mat-table [dataSource]="eventos" class="full-width-table" matSort aria-label="Elements">

标签: angulartypescriptangular-material-table

解决方案


当您运行 connect 时,这些变量中的一个或全部没有值并且未定义。

data: EventoTableItem[] = EVENTOS;
paginator: MatPaginator;
sort: MatSort;

所以这就是为什么它说 connect 有一个未定义的值,因为 this.paginator.page 没有初始化。

我假设那是因为您之前运行过连接:

ngAfterViewInit() {


     this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;
        this.table.dataSource = this.dataSource;
      }

将其放入 ngAfterViewInit 而不是 ngOnInit() 是否有特定原因?


推荐阅读