繁体   English   中英

Angular 材料 - Mat-table 不显示来自 REST 的数据 API

[英]Angular Material - Mat-table not displaying data from REST API

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

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

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

帐户列表.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;
    });
  }

}

账户管理服务.ts

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

帐户列表-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]));
    }));
  }

结果

该表应该包含一条记录

解决了! 我忘记在 html 模板中为 mat-table 设置数据源

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM