我正在使用mat-table,并且尝试将 MatTableDataSource 与可观察的(我从Web服务获取数据)一起使用,但是我不知道如何配置< em> 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;
});
}
答案 0 :(得分:17)
您应该能够在班级级别一次刷新MatTableDataSource
,然后在data
中使用ngOnInit
设置器。
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;
});
}
答案 1 :(得分:0)
您也可以使用可观察的,只需(*)
[dataSource]="dataSource|async"
(*)确实不需要使用管道异步
请参见stackblitz中的示例,在该示例中,我将doc的第一个示例替换为
dataSource = of(ELEMENT_DATA).pipe(delay(1000));
答案 2 :(得分:0)
我为此发布了一个库:@matheo/datasource
我在本文中解释了基本概念:
https://medium.com/@matheo/reactive-datasource-for-angular-1d869b0155f6
以及示例代码中,您可以看到我如何从Firebase数据库中获取项目并操纵分页。示例存储库中的排序和过滤器
希望您喜欢它,并给我您的意见;)
答案 3 :(得分:0)
这是一种解决方法,因为 MatTableDataSource 不支持 Observable 作为数据源
import { MatTableDataSource } from '@angular/material';
import { Observable, Subscription } from 'rxjs';
import { SomeInterface} from './some.interface';
export class CustomDataSource extends MatTableDataSource<SomeInterface> {
private collection: SomeInterface[] = [];
private collection$: Subscription;
constructor(collection: Observable<SomeInterface[]>) {
super();
this.collection$ = collection.subscribe(data => {
this.data = data; // here you have to adjust the behavior as needed
});
}
disconnect() {
this.collection$.unsubscribe();
super.disconnect();
}
}
然后在组件中:
dataSource: CustomDataSource;
ngOnInit(): void {
const observableData$ = getData();
this.dataSource = new CustomDataSource(observableData$);
// this.dataSource.sort = this.sort; // add sorting or filter
}
示例:stackblitz