Update Data Using PUT API - Edit User Example, HttpClient
PUT API is used to update existing data.
In this example, we update user name, age, and email using PUT API.
What is happening in the UI
- User list is shown with an Edit button
- Click on Edit button
- User is navigated to Edit User page
- Old data is already filled in input fields
- Change the values
- Click Update User
- Data gets updated and user goes back to list
Testing PUT API with Thunder Client
- Select method: PUT
- URL format:
http://localhost:3000/users/id
- ID is passed at the end of URL
- Updated data is sent in body
- After send, data gets updated in JSON server
Edit Button (User List HTML)
<button (click)="editUser(user.id)">Edit</button>
This sends user ID to edit page.
Getting User ID in Edit Component
let id = this.activeRouter.snapshot.paramMap.get('id');
This gets the user ID from the URL.
editUser() Function (Update Logic)
editUser(){
let name = this.name.value;
let age = this.age.value;
let email = this.email.value;
let id = this.activeRouter.snapshot.paramMap.get('id');
if(name && age && email && id){
let data = {
name: name,
age: Number(age),
email: email,
}
this.userService.userEdit(data, id).subscribe((item)=>{
this.router.navigate(['/'])
})
}
}
Meaning of the Code
- Get updated values from input fields
- Get user ID from route
- Check all values exist
- Create data object
- Convert age to number
- Call PUT API using service
- After success, go back to user list