Back to course

Managing PUT/DELETE Requests (Updating/Deleting Resources)

The Complete Angular Developer: From Zero to Hero

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) { const url = ${this.baseUrl}/posts/${id}; // HttpClient.put() requires the ID in the URL and the update payload return this.http.put(url, updatedData); }

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(url); }

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