0

I have an angular 7 material project that requires me to display a list of cars in Angular material table. The cars are populated from asp.net core back end. So far, everything works as it should except for dynamically altering/deleting cars, and having the changes implemented on the fly. Essentially, I'm trying to refresh the data source.

I've followed an example from this site => Angular + Material - How To Refresh A Data Source (mat-table) but with no success.

Where am I going wrong?

So far, what I've tried is using this code to refresh the getAllCars() function and the edit and delete functions:

this.datasource.connect().next(res); and tried: this.carModels= new MatTableDataSource<Element>(this.carModels);

Service

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

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

TS file

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

Remove Car

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

1 Answers1

0

Once the mat-table connects with the DataSource, you can only provide new information though the DataSource itself.

I encourage you to use @matheo/datasource to have clean separation of concerns, manipulate your data only in the corresponding services (database and datasource) without worries about new features to implement, and just calling reload() when you need to refresh the list after some edition/deletion.

I wrote about this library and built a friendly demo:
https://medium.com/@matheo/reactive-datasource-for-angular-1d869b0155f6

I can support your use case if you like it.
Happy coding!

Mateo Tibaquira
  • 2,059
  • 22
  • 23