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

Angular mat-table: How to refresh datasource with updated resource as response?

我正在使用 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);
              });
            }
          );
}

你可以试试。假设您的补丁 returns 更新文章。

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

//你也可以试试..可能会有帮助

  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; 

   });