,

Updating Data with API in Angular CLI: Angular CRUD – Part 3

Posted by






Angular CRUD – Edit and Update Data

Angular CRUD – Edit and Update Data

In the previous articles, we have learned how to create and read data using Angular CLI and API. In this article, we will focus on editing and updating data using API in Angular.

Edit Data in Angular

First, let’s create a form to edit the data. We can use Angular’s built-in forms module to create a form and populate it with the existing data.

“`html








“`

In the form above, we bind the input fields to the existing data using Angular’s interpolation syntax. When the form is submitted, we will call the updateData method to send the updated data to the API.

Update Data with API

Now, let’s implement the updateData method to send the updated data to the API.

“`javascript
export class DataService {
constructor(private http: HttpClient) { }

updateData(id: number, updatedData: any): Observable {
return this.http.put(`https://api.example.com/data/${id}`, updatedData);
}
}
“`

In the DataService class, we create a method called updateData that takes the ID of the data to be updated and the updated data as parameters. This method makes a PUT request to the API endpoint with the updated data.

Now, we need to call the updateData method when the form is submitted.

“`javascript
export class EditComponent {
constructor(private dataService: DataService, private route: ActivatedRoute) { }

data: any;

ngOnInit() {
const id = this.route.snapshot.params.id;
this.dataService.getDataById(id).subscribe((data) => {
this.data = data;
});
}

updateData() {
const id = this.route.snapshot.params.id;
this.dataService.updateData(id, this.data).subscribe((response) => {
console.log(‘Data updated successfully’, response);
});
}
}
“`

In the EditComponent class, we call the updateData method when the form is submitted. We also retrieve the ID of the data to be updated from the URL using Angular’s ActivatedRoute module.

With the above implementation, we can edit and update data using API in Angular. This completes the CRUD (Create, Read, Update, Delete) operations in Angular.


0 0 votes
Article Rating
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Eran Dahan
10 months ago

Can you upload code to github ?

medoune cisse
10 months ago

hi sir,
can you add login functionality to this series ?

Gamer Boy
10 months ago

Sir you haven't make video on laravel many to many relation

John Kiyaka
10 months ago

Thank you ..all the way from kenya