# 3. The component
In the previous tutorial, we developed the getCars() method that brings the list of cars.
In this one, we'll write the addCars() method that adds a car.
You need to initialize the car object by implementing the Car interface
which requires the model and price fields:
src/app/app.component.ts
car: Car = {model:'', price:0};
Now, you can add the addCar() method that receives the values entered into the
form before sending them to the service.
Add the following code beneath the getCars() method:
src/app/app.component.ts
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)
);
}
The f parameter is of type NgForm so it holds everything that Angular thinks you need to know about the form that we're going to build in the next part of the tutorial.
In the case of success, Angular's reset() method will reset the form, including the values and classes.
addCar() sends the values that the users feed the form with to the store() method of the service, and subscribes to the output.
The store() method is an observable and so addCar() needs to subscribe to it in order to send the data to the service.
To improve your understanding read the tutorial about Observables.
We expect the Observable to return one of two results: success or failure.
The full code for the component needs to look something like this:
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) => {
console.log(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)
);
}
resetAlerts() {
this.error = '';
this.success = '';
}
}