如何将MatTableDataSource与可观察对象一起使用? [英] How to use the MatTableDataSource with an observable?

查看:23
本文介绍了如何将MatTableDataSource与可观察对象一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MAT表,并且正在尝试将MatTableDataSource用于可观察对象(我从Web服务获取数据),但我不知道如何将MatTableDataSource配置为使用可观察对象而不是数组。

此问题的唯一解决方案是订阅ngOnInit方法中的可观测对象,并在新数据到达时始终创建新的MatTableDataSource吗?

这是我到目前为止拥有的全部信息,但我不知道这是否是将MatTableDataSource与可观察对象一起使用的正确解决方案。

dataSource: MatTableDataSource<Thing>;
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
@ViewChild(MatSort, { static: true }) sort: MatSort;

ngOnInit() {
    getThings().subscribe(things => {
        this.dataSource = new MatTableDataSource(things);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
        });
}

推荐答案

您应该能够在类级别新建MatTableDataSource一次,然后在ngOnInit中使用data设置器。

dataSource = new MatTableDataSource<Thing>();
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
@ViewChild(MatSort, { static: true }) sort: MatSort;

ngOnInit() {
    getThings().subscribe(things => {
        this.dataSource.data = things;
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
    });
}

这篇关于如何将MatTableDataSource与可观察对象一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆