首页 > 解决方案 > Angular - 从数组更改中刷新垫表

问题描述

我有一个应用调用观察器,由一个组件/服务组成。我有一个简单的表格,可以正确显示为空

    <table mat-table [dataSource]="this.getWatcherTable()" class="mat-elevation-z8">
  
        ... my columns and rows are described here

    </table>

源链接到我的组件文件

export class WatcherComponent{

    constructor(public watcherService : WatcherService ) {}

    getWatcherTable(){
        return this.watcherService.watcherTable;
    }
}

本身链接到服务文件

export class WatcherService {
    watcherTable : Array<Watcher> = new Array();

    updateWatchers(name,value){
        this.watcherTable.push({name:name, value:value});
    }
}

更新由另一个应用程序触发并且运行良好,数组的控制台日志有更新,但数组仍然显示为空

标签: angulartypescriptmat-table

解决方案


每次更新数组时,都应该创建一个新数组,以便 Angular 更改检测会自动更新组件。所以与其:

export class WatcherService {
    watcherTable : Array<Watcher> = new Array();

    updateWatchers(name,value){
        this.watcherTable.push({name:name, value:value});
    }
}

你应该有:

export class WatcherService {
    watcherTable : Array<Watcher> = new Array();

    updateWatchers(name,value){
        this.watcherTable = this.watcherTable.concat([{name:name, value:value}]);
    }
}


推荐阅读