4
votes

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

2
You can examine material docs example: stackblitz.com/angular/… this link don't working because angular 5 package cause to crash. However you can look the code.Murat Çimen
@MuratÇimen Here's an updated example: stackblitz.com/edit/angular-6dm7mvEdric
thanks Murat and Edric, Do you know if there is a function that cleans the table?Manuel Novoa

2 Answers

1
votes

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

-1
votes

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