# 2. The component
Add the updateCar() method to the component. The method gets the values from the form and subscribes to the update() method in the service.
src/app/app.component.ts
updateCar(name: any, price: any, id: any) {
this.resetAlerts();
this.carService
.update({ model: name.value, price: price.value, id: +id })
.subscribe(
(res) => {
this.success = 'Updated successfully';
},
(err) => (this.error = err)
);
}
The method updateCar() subscribes to the update() method in the service since it is an observable,
and so the update() method returns one of two results:
- In the case of an error, the method exposes the error message to the user.
- In the case of success, the method will print a success message.
The full code of the component:
src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Car } from './car';
import { CarService } from './car.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
cars: Car[] = [];
car: Car = { model: '', price: 0 };
error = '';
success = '';
constructor(private carService: CarService) {}
ngOnInit() {
this.getCars();
}
getCars(): void {
this.carService.getAll().subscribe(
(data: Car[]) => {
this.cars = data;
this.success = 'Success in retrieving the list';
},
(err) => {
this.error = err.message;
}
);
}
addCar(f: NgForm) {
this.resetAlerts();
this.carService.store(this.car).subscribe(
(res: Car) => {
// Update the list of cars
this.cars.push(res);
// Inform the user
this.success = 'Created successfully';
// Reset the form
f.reset();
},
(err) => (this.error = err.message)
);
}
updateCar(name: any, price: any, id: any) {
this.resetAlerts();
this.carService
.update({ model: name.value, price: price.value, id: +id })
.subscribe(
(res) => {
this.success = 'Updated successfully';
},
(err) => (this.error = err)
);
}
resetAlerts() {
this.error = '';
}
}