PUT and DELETE requests let your app update or remove data on a server. They help keep your app's data fresh and accurate.
0
0
PUT and DELETE requests in Angular
Introduction
When you want to change existing information, like updating a user's profile.
When you need to remove an item, like deleting a post or comment.
When syncing changes from your app to the server to keep data consistent.
When building features like edit forms or delete buttons in your app.
Syntax
Angular
this.httpClient.put(url, body, options) this.httpClient.delete(url, options)
PUT sends the full updated data to replace existing data.
DELETE removes data identified by the URL.
Examples
Updates user with ID 1 to have name 'Anna' and age 30.
Angular
this.httpClient.put('https://api.example.com/users/1', {name: 'Anna', age: 30})
Deletes user with ID 1 from the server.
Angular
this.httpClient.delete('https://api.example.com/users/1')
Sample Program
This Angular component has two buttons. Clicking 'Update User' sends a PUT request to change user data. Clicking 'Delete User' sends a DELETE request to remove the user. The message below shows success or failure.
Angular
import { Component } from '@angular/core'; import { HttpClient, HttpClientModule } from '@angular/common/http'; @Component({ selector: 'app-user-manager', template: ` <button (click)="updateUser()">Update User</button> <button (click)="deleteUser()">Delete User</button> <p>{{message}}</p> `, standalone: true, imports: [HttpClientModule] }) export class UserManagerComponent { message = ''; constructor(private httpClient: HttpClient) {} updateUser() { const url = 'https://jsonplaceholder.typicode.com/users/1'; const updatedData = { name: 'Anna', username: 'anna123' }; this.httpClient.put(url, updatedData).subscribe({ next: () => this.message = 'User updated successfully!', error: () => this.message = 'Failed to update user.' }); } deleteUser() { const url = 'https://jsonplaceholder.typicode.com/users/1'; this.httpClient.delete(url).subscribe({ next: () => this.message = 'User deleted successfully!', error: () => this.message = 'Failed to delete user.' }); } }
OutputSuccess
Important Notes
Always handle errors to inform users if the request fails.
PUT replaces the entire resource, so send all required fields.
DELETE requests usually don't need a body, just the URL identifying the item.
Summary
PUT updates existing data by sending the full new version.
DELETE removes data identified by the URL.
Use Angular's HttpClient to easily send these requests and handle responses.