1
votes

I am using a mat-table to show a list of articles. I can change the price of different articles. After updating the price of the article I am getting back the updated article (updated resource). I want to refresh my datasource without having to call the getArticles and load all the articles because I have already the updated article.

So I can update the datasource replacing the old for the updated item or which is the proper way to do that?

private updateArticle(value: any, id: string): void {
    this.dataService.patchArticle(id,price)
        .subscribe(
            article => {
               this.dataService.getArticles(); //that is unnecessary, I have the updated article in variable 'article'
               //this.replaceArticleDatasource(article) //update datasource
              .subscribe(
                  data => {
                    this.articles = data;
                    this.dataSource = new MatTableDataSource(this.articles);
              });
            }
          );
}
2
It is a long story. AFAIK MatTableDataSource is run on the client-side. So all of your table's features like pagination, sorting, filtering will be work on the client-side too even if you change your data source and all the time you refresh your data I guess all of the table feature will be reseting. For this reason I think is is not good to change the datasource.Seyhmus Gokcen
So, you have to code on your own a datasource lies on RxJS observable to run it on serverside and get the behavior you desire. I highly recommend to follow this article : blog.angular-university.io/angular-material-data-tableSeyhmus Gokcen

2 Answers

2
votes

You could try. Assuming your patch returns the updates article.

private updateArticle(value: any, id: string): void 
{
    this.dataService.patchArticle(id,price).subscribe(article => {
    this.atricles.find(x => x.id === article.id) = article;

    this.dataSource.data = this.articles;
});
0
votes

// you can also try ..It may help

  datasource:any;

  @ViewChild(MatPaginator) paginator: MatPaginator;

  @ViewChild(MatSort) sort: MatSort;


  private updateArticle(value: any, id: string): void 
  {
    this.dataService.patchArticle(id,price).subscribe(article => 
    {
      this.datasource = new MatTableDataSource();

      let article_filtered =

      this.article.find(data => data.id === article.id);

      this.datasource.data = article_filtered;

      **// for sorting in mat table**

      this.datasource.sort = this.sort;

      **// for pagination in mat table** 

      this.datasource.paginator = this.paginator; 

   });