28. Managing PUT/DELETE Requests
1. PUT Requests (Updating)
PUT requests are used to update an entire resource on the server. Similar to POST, they require a payload (the updated data) and typically include the resource ID in the URL path.
typescript // data.service.ts
updatePost(id: number, updatedData: Partial${this.baseUrl}/posts/${id};
// HttpClient.put() requires the ID in the URL and the update payload
return this.http.put
In the component, you subscribe and often don't need the returned object, only confirmation of success.
typescript
// component.ts
updateExistingPost(id: number) {
const patch = { title: 'Updated Title' };
this.dataService.updatePost(id, patch).subscribe(() => {
console.log(Post ${id} updated.);
});
}
2. DELETE Requests (Deleting)
DELETE requests remove a resource. They only require the resource identifier (ID) in the URL and typically do not require a body.
typescript // data.service.ts
deletePost(id: number) {
const url = ${this.baseUrl}/posts/${id};
// The response type is often void or an empty object {}
return this.http.delete
In the component:
typescript
// component.ts
deleteItem(id: number) {
this.dataService.deletePost(id).subscribe({
next: () => {
alert(Post ${id} successfully deleted.);
// Refresh the list locally
},
error: (e) => {
console.error('Failed to delete:', e);
}
});
}