I try to create a delete method but it doesn't work, I use json-server with reactive forms, my description of the problem is quite simple because what I ask is quite simple I'm a junior trying to figure out how it all works.
i have an error : ERROR TypeError: product is undefined
ts.file
export class ProduitsComponent implements OnInit {
public dataSource: MatTableDataSource<Produit>;
constructor(private produitService: ProduitService, public dialog: MatDialog) { }
ngOnInit() {
this.getLatestProduct();
}
createNewProduct(product: any) {
this.produitService.createProduct(product).subscribe((response: Produit) => {
let t = this.dataSource.data;
t.push(response);
this.dataSource.data = t;
});
}
updateLatestProduct(product: Produit) {
this.produitService.updateProduct(product).subscribe(response => {
let index = this.dataSource.data.findIndex((value) => {value.id === product.id});
this.dataSource.data.splice(index, 1, response);
});
}
getLatestProduct() {
let resp = this.produitService.getAllProduct();
resp.subscribe(result => {
this.dataSource = new MatTableDataSource<Produit>();
this.dataSource.data = result as Produit[];
});
}
delete(product: Produit) {
this.produitService.deleteProduct(product).subscribe(() => {
this.dataSource.data.filter((value, key) => {
return value.id != product.id;
});
});
}
service
public deleteProduct(product: Produit) {
return this.httpClient.delete(`${this.urlProductApi}produits/${product.id}`);
}
html
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
......
<!-- Comment Column -->
<ng-container matColumnDef="comment">
<th class="text" mat-header-cell *matHeaderCellDef>Commentaire</th>
<td class="text2" mat-cell *matCellDef="let element"> {{element.comment}} </td>
</ng-container>
<!-- Action Column-->
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef> Action </th>
<td mat-cell *matCellDef="let row">
<button mat-raised-button color="primary" (click)="editFormDialog(row)">Edit</button>
<button mat-raised-button color="warn" (click)="delete()">Supprimer</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>