如何使用angular4将数据绑定到mat-table dataSource?

时间:2017-12-01 15:02:50

标签: javascript angular angular-material2

我有一个材料数据表,我试图动态设置dataSource但它抛出错误dataSource未定义,我是angular2的新手,请帮助我理解下面的代码是否有问题。

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;
}

1 个答案:

答案 0 :(得分:1)

我认为在this.socket.on('newMessage'解析之前会触发this.streamService.getAllStream()事件,所以必须等到dataSource实例化后才会发生:

  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]
        });
    });
}