Search⌘ K
AI Features

Modifying Data Through HTTP

Explore how to modify data through HTTP in Angular by creating components to add, update, and delete products. Understand integrating HttpClient for CRUD operations and event handling between components to update and manage product lists dynamically.

We'll cover the following...

Modifying data in a CRUD application usually refers to adding new data and updating or deleting existing data. To demonstrate how to implement such functionality in an Angular application using the HttpClient service, we will make the following changes to our application:

  • Create an Angular component to add new products.

  • Modify the product detail component to change the price of an existing product.

  • Add a button in the product detail component for deleting an existing product.

We will start with the component for adding new products.

Adding new products

To add a new product through our application, we need to send the name and price of a new product into the Fake Store API. Before implementing the required functionality for adding products, we must refactor the ProductListComponent class in the product-list.component.ts file as follows:

TypeScript 4.9.5
export class ProductListComponent implements OnInit {
selectedProduct: Product | undefined;
products: Product[] = [];
constructor(private productService: ProductsService) {}
ngOnInit(): void {
this.getProducts();
}
onBuy() {
window.alert('You just bought ${this.selectedProduct?.name}!');
}
private getProducts() {
this.productService.getProducts().subscribe(products => {
this.products = products;
});
}
}

We may ask ourselves why we are doing this. The ...