【问题标题】:Angular Material - Mat-table not displaying data from REST APIAngular Material - Mat-table 不显示来自 REST API 的数据
【发布时间】:2020-12-18 18:09:25
【问题描述】:

我一直在尝试实现一个带有分页和排序的垫表,但没有运气。

我完全迷失了 datasource.ts 文件。

当我记录 this.dataSource.data 时,会显示数据,但是当我在 ngOnInit 中的 this.getUsers() 之后记录 this.dataSource.data 时,它会返回 undefined

account-list.component.ts

@Component({
  selector: 'app-account-list',
  templateUrl: './account-list.component.html',
  styleUrls: ['./account-list.component.css']
})
export class AccountListComponent implements OnInit {
  @ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
  @ViewChild(MatSort, {static: false}) sort: MatSort;
  @ViewChild(MatTable, {static: false}) table: MatTable<AccountListItem>;
  dataSource: AccountListDataSource;
  data: User[];

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  constructor(private accountManagementService: AccountManagementService) {
  }

  ngOnInit() {
    this.dataSource = new AccountListDataSource();
    this.getUsers();
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  getUsers() {
    this.accountManagementService.getAllAccounts().subscribe((response:any) => {
      this.dataSource.data = response.content;
    });
  }

}

accountManagement.service.ts

getAllAccounts(): Observable<any> {
    return Observable.create(observer => {
      this.apiService.get({
        endPoint: `/${this.PREFIX}/`
      }).subscribe((responseData) => {
        observer.next(responseData);
      });
    });
  }

account-list-datasource.ts

export class AccountListDataSource extends DataSource<User> {
  data: User[] = [];
  paginator: MatPaginator;
  sort: MatSort;


  constructor() {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<User[]> {
    // 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
    ];

    this.paginator.length = this.data.length;

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

结果

【问题讨论】:

  • 您是否将 dataSource 设置为 'account-list.component.html' 模板中的 mat-table?

标签: angular typescript angular-material


【解决方案1】:

解决了!我忘了在 html 模板中为 mat-table 设置 dataSource

【讨论】:

    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 2019-06-03
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    相关资源
    最近更新 更多