Can someone please help, I have encountered this issue - after confirming the deletion the table data doesn't update. Deletion works, but I don't want to refresh the page all the time.
I have tried to subscribe and unsubscribe in table component, adding deletion function to table component, however, with no luck.
Delete compononent.ts
import { Component} from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { CarService } from 'src/app/services/car.service';
@Component({
selector: 'app-delete-car',
templateUrl: './delete-car.component.html',
styleUrls: ['./delete-car.component.scss']
})
export class DeleteCarComponent {
constructor(public carService: CarService, private _snackBar: MatSnackBar) { }
performDelete(id: string): void {
if(id){
this.carService.deleteCar(id).subscribe(() => {
this._snackBar.open("Record deleted successfuly");
}, () => {
this._snackBar.open("Oops, something went wrong :(");
});
}
}
}
delete html:
<div mat-dialog-content>
<p>Are you sure you want to delete?</p>
</div>
<div mat-dialog-actions>
<button mat-button mat-dialog-close="cancel">No Thanks</button>
<button mat-button mat-dialog-close="delete">Yep!</button>
</div>
Table component:
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator} from '@angular/material/paginator';
import { CarService } from 'src/app/services/car.service';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { Car } from 'src/app/types';
import { MatDialog } from '@angular/material/dialog';
import { DeleteCarComponent } from '../delete-car/delete-car.component';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({
selector: 'app-car-list',
templateUrl: './car-list.component.html',
styleUrls: ['./car-list.component.scss']
})
export class CarListComponent implements OnInit{
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
allCars: Car[];
columnsToDisplay = ['carplate', 'ownername', 'actions'];
dataSource: MatTableDataSource<Car>;
constructor(private carService: CarService, public dialog: MatDialog, private _snackBar: MatSnackBar,
public deleteCar: DeleteCarComponent) { }
ngOnInit(){
this.carService.allCars().subscribe(data => {
this.allCars=data.sort((a: { car_plate: string; }, b: { car_plate: any; }) => a.car_plate.localeCompare(b.car_plate));
this.dataSource = new MatTableDataSource(this.allCars);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
});
}
filterData($event: any) {
this.dataSource.filter = $event.target.value;
}
openDeleteConfirmation(id: string) {
const dialogRef = this.dialog.open(DeleteCarComponent);
dialogRef.afterClosed().subscribe(response => {
if(response == 'delete') {
this.deleteCar.performDelete(id);
}
})
}
}