angular - 如何使用 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">
解决方案
当您运行 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() 是否有特定原因?
推荐阅读
- git - git:看起来不像分支的分支
- android - Android 构建 beta APK 并通过 circleci 发布 APK
- django - WebSocket 失败:WebSocket 握手期间出错
- javascript - 如何使用 localStorage 值选择复选框
- sql - 从表 MSSQL 服务器解析保存的 xml
- tcp - 如何在openresty lua中使用第一个字节内容将tcp请求发送到后端
- css - 具有粘性页眉和页脚以及动态内容高度的 Angular 2 组件
- javascript - CKEditor 5 注册多个上传适配器
- php - PHP 创建表单到 CSV 并作为附件发送到电子邮件
- java - 如何验证 Firebase id 令牌