Reputation: 7123
I have a material data table that i am trying to set dataSource dynamically but it throws error dataSource
undefined, I am new to angular2 please help me to understand if below code has some issue.
stream.component.html
<mat-table #table [dataSource]="dataSource">
<mat-table #table [dataSource]="dataSource">
<!-- Position Column -->
<ng-container matColumnDef="ticketNum">
<mat-header-cell *matHeaderCellDef> Ticket Number </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.ticketNum}} </mat-cell>
</ng-container>
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;
}
Upvotes: 1
Views: 4780
Reputation: 37413
I think that this.socket.on('newMessage'
event is fired before this.streamService.getAllStream()
resolves, so have to wait until the dataSource is instantiated :
this.streamService.getAllStream().subscribe(stream => {
this.dataSource = new MatTableDataSource(stream);
this.socket.on('newMessage', (event) => { // <-- here
console.log('Datasource', event);
this.dataSource.data.push(event);
this.dataSource.data = [...this.dataSource.data]
});
});
}
Upvotes: 1