0

我有一个 Angular 7 材质项目,需要我在 Angular 材质表中显示汽车列表。这些汽车是从 asp.net 核心后端填充的。到目前为止,除了动态更改/删除汽车以及动态实施更改之外,一切都正常运行。本质上,我正在尝试刷新数据源。

我遵循了这个站点的一个例子=> Angular + Material - 如何刷新数据源(mat-table)但没有成功。

我哪里错了?

到目前为止,我尝试使用此代码刷新getAllCars()函数以及编辑和删除函数:

this.datasource.connect().next(res); 并尝试: this.carModels= new MatTableDataSource<Element>(this.carModels);

服务

  removeCarModel(id: number) {
    return this.http.delete(this.URL+ 'cars/deleteCar/' + id);
  }

 getAllCarModels() {
    return this.http.get(this.URL+ `cars/getAllCars`);
  }

TS文件

getAllCars() {
    this.carService.getAllCarModels().subscribe(
      res => {
        this.carModels = res;
        this.dataSource= new MatTableDataSource();
        this.dataSource.data = res;
        this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;

        // Tried the below. They don't work
        // this.carModels = new MatTableDataSource<Element>(this.carModels );
        // this.datasource.connect().next(res);

      },
      error => {
        console.log("Error");
      }
    );
  }

移除汽车

removeCar: any;
  removeSelectedCar(id) {
      this.carService.removeCarModel(id).subscribe(
        res => {
          this.removeCar = res;

         // Tried the below. They don't work
         // this.dataSource.connect().next(res);
         // this.removeCar= new MatTableDataSource<Element>(this.removeCar);

          console.log("Successfully deleted");
        },
        error => {
          console.log("Error");
        }
      );
  }

editCar: any;
  editSelectedCar() {
    this.carService.editCarModel(this.Id, this.carModel).subscribe(res=> {
    console.log("Successfully edited");
    this.editCar = res;

 // Tried the below. They don't work
         // this.dataSource.connect().next(res);
         // this.editCar = new MatTableDataSource<Element>(this.editCar);

    }, error => {
      console.log("Error");
    }
    );
  }

4

1 回答 1

0

一旦mat-table与 DataSource 连接,您只能通过 DataSource 本身提供新信息。

我鼓励您使用@matheo/datasource干净的关注点分离,仅在相应的服务(数据库和数据源)中操作您的数据,而不用担心要实现的新功能,并且只reload()在您需要在某些版本/删除后刷新列表时调用。

我写了关于这个库并构建了一个友好的演示:
https ://medium.com/@matheo/reactive-datasource-for-angular-1d869b0155f6

如果您喜欢,我可以支持您的用例。
快乐编码!

于 2019-06-18T20:21:16.180 回答