Angular Mat-Table:如何使用更新的资源作为响应来刷新数据源?

时间:2019-03-06 21:39:56

标签: angular angular-material mat-table

我正在使用mat-table来显示文章列表。我可以更改其他商品的价格。更新商品价格后,我将取回更新的商品(更新的资源)。我想刷新数据源而不必调用getArticles并加载所有文章,因为我已经更新了文章。

所以我可以更新数据源,用旧的代替更新的项目,或者这样做的正确方法是什么?

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 个答案:

答案 0 :(得分:2)

您可以尝试。假设您的补丁返回了更新文章。

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

答案 1 :(得分:0)

//您也可以尝试..可能有帮助

  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; 

   });