如何将数据动态添加到 mat-table 数据源? [英] How to add data dynamically to mat-table dataSource?
问题描述
我有来自后端的数据流,我看到它在控制台中打印,现在我正在尝试将事件推送到 dataSource
其抛出的错误数据源未定义.有人可以帮助如何动态添加数据以实现表吗?
I have data streaming from backend and i see it printing in console now i am trying to push event to dataSource
its throwing error dataSource is not defined. Can someone help how to dynamically add data to materialize table ?
stream.component.html
stream.component.html
<mat-table #table [dataSource]="dataSource"></mat-table>
stream.component.ts
stream.component.ts
import {
Component,
OnInit
} from '@angular/core';
import {
StreamService
} from '../stream.service';
import {
MatTableDataSource
} from '@angular/material';
import * as io from 'socket.io-client';
@Component({
selector: 'app-stream',
templateUrl: './stream.component.html',
styleUrls: ['./stream.component.css']
})
export class StreamComponent implements OnInit {
displayedColumns = ['ticketNum', "assetID", "severity", "riskIndex", "riskValue", "ticketOpened", "lastModifiedDate", "eventType"];
dataSource: MatTableDataSource < Element[] > ;
socket = io();
constructor(private streamService: StreamService) {};
ngOnInit() {
this.streamService.getAllStream().subscribe(stream => {
this.dataSource = new MatTableDataSource(stream);
});
this.socket.on('newMessage', function(event) {
console.log('Datasource', event);
this.dataSource.MatTableDataSource.filteredData.push(event);
});
}
}
export interface Element {
ticketNum: number;
ticketOpened: number;
eventType: string;
riskIndex: string;
riskValue: number;
severity: string;
lastModifiedDate: number;
assetID: string;
}
推荐答案
我已经找到了解决这个问题的方法,基本上如果你这样做:
I have found a solution for this problem, basically if you do:
this.dataSource.data.push(newElement);//不起作用
但是如果您替换完整的数组,则它可以正常工作.所以你的最终代码必须是:
But if you replace the complete array then it works fine. So your final code must be :
this.socket.on('newMessage', function(event) {
const data = this.dataSource.data;
data.push(event);
this.dataSource.data = data;
});
您可以在此处查看问题 -> https://github.com/angular/material2/问题/8381
You can see the issue here -> https://github.com/angular/material2/issues/8381
这篇关于如何将数据动态添加到 mat-table 数据源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!