Angular Material 2: How to refresh md-table after add data to datasource?

北城余情 提交于 2019-12-12 16:28:45

问题


Could someone put a complete example of a mat-table with datasource adding a data later on when the table is loaded and the table is updated?

My program manages to show the table, the load of data, the dialog box that asks for the new data, the data to add to the database, but I do not know how to refresh the table

I found this example

    connect(): Observable<UserVModel[]> {
  return this._userService.dataChanged
      .switchMap(() => this._userService.getAllUsers()
}

in this link: Angular Material 2: How to refresh md-table after editing a record?

But I do not know how to implement it.

Thank you


回答1:


There are several ways to implement what you ask. This is what I use in my projects:

This implements an abstraction of the data source:

class DataSourceManager<T> {
    private readonly manualSource = new Subject<T>();

    constructor(private readonly source: Observable<T>) {

    }

    public getObserver(): Observable<T> {
        return merge(
            this.source,
            this.manualSource,
        );
    }

    public reload(): void {
        this.source.subscribe(x => {
            this.push(x);
        });
    }

    public push(value: T): void {
        this.manualSource.next(value);
    }
}

This is the dataset typed on MyItem, fetch by MyItemService (these are trival and out of scope):

class MyDataSource extends DataSource<MyItem> {

    public readonly manager: DataSourceManager<MyItem[]>;

    constructor(private readonly myService: MyItemService) {
        super();

        this.manager = new DataSourceManager<MyItem[]>(
            this.myService.getAllItemsObserver();
    }

    public connect(): Observable<MyItem[]> {
        return this.manager.getObserver();
    }

    public disconnect() {
    }
}

Now, when you need to manually update the data source, simply call dataSource.manager.push




回答2:


You could just push the result to the array using yourarray.push(your new object). (after adding a new record)



来源:https://stackoverflow.com/questions/47897694/angular-material-2-how-to-refresh-md-table-after-add-data-to-datasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!