Last active
October 21, 2019 00:34
-
-
Save fexx/0842427b04891d499dd36618d2a3e646 to your computer and use it in GitHub Desktop.
app.component.ts (Consumindo API REST com HttpClient no Angular 8)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core'; | |
import { CarService } from './services/car.service'; | |
import { Car } from './models/car'; | |
import { NgForm } from '@angular/forms'; | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.css'] | |
}) | |
export class AppComponent implements OnInit { | |
car = {} as Car; | |
cars: Car[]; | |
constructor(private carService: CarService) {} | |
ngOnInit() { | |
this.getCars(); | |
} | |
// defini se um carro será criado ou atualizado | |
saveCar(form: NgForm) { | |
if (this.car.id !== undefined) { | |
this.carService.updateCar(this.car).subscribe(() => { | |
this.cleanForm(form); | |
}); | |
} else { | |
this.carService.saveCar(this.car).subscribe(() => { | |
this.cleanForm(form); | |
}); | |
} | |
} | |
// Chama o serviço para obtém todos os carros | |
getCars() { | |
this.carService.getCars().subscribe((cars: Car[]) => { | |
this.cars = cars; | |
}); | |
} | |
// deleta um carro | |
deleteCar(car: Car) { | |
this.carService.deleteCar(car).subscribe(() => { | |
this.getCars(); | |
}); | |
} | |
// copia o carro para ser editado. | |
editCar(car: Car) { | |
this.car = { ...car }; | |
} | |
// limpa o formulario | |
cleanForm(form: NgForm) { | |
this.getCars(); | |
form.resetForm(); | |
car = {} as Car; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment