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