【问题标题】:Angular mat-table: How to refresh datasource with updated resource as response?Angular mat-table:如何使用更新的资源作为响应刷新数据源?
【发布时间】:2019-07-28 16:17:12
【问题描述】:

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

【问题讨论】:

  • 说来话长。 AFAIK MatTableDataSource 在客户端运行。因此,即使您更改数据源并且一直刷新数据,您的表格的所有功能(例如分页、排序、过滤)也将在客户端工作,我猜所有表格功能都将被重置。因此,我认为更改数据源并不好。
  • 因此,您必须自己编写一个位于 RxJS observable 上的数据源,以便在服务器端运行它并获得您想要的行为。我强烈推荐关注这篇文章:blog.angular-university.io/angular-material-data-table

标签: angular angular-material mat-table


【解决方案1】:

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

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

【讨论】:

  • 在更新文章时使用这种方式创建新的 MatTableDataSource。
  • @DhanikaThathsaraMunasinghe 有问题吗?我的意思是,更新文章时创建一个新的 MatTableDataSource
  • @MrScf 我认为您可以在不创建新的 MatTableDataSource 的情况下更新数据源。
  • 像这样:this.myService.doSomething().subscribe(data: MyDataType[] => { this.dataSource.data = data; }
  • 在我的项目中,您仍然需要使用 window.location.reload() 刷新页面。 ....
【解决方案2】:

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

  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; 

   });

【讨论】:

  • 文章是一个对象,而不是对象列表。所以不能将文章设置为this.datasource.data
猜你喜欢
  • 2018-03-26
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-08
  • 2020-03-09
  • 2018-05-08
相关资源
最近更新 更多