问题描述
我有来自后端的数据流,我现在正在控制台中看到它正在打印,我正在尝试将事件推送到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); //Doesn't work
但是,如果您替换整个阵列,则可以正常工作.因此,您的最终代码必须是:
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 dataSource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!