Skip to content

Instantly share code, notes, and snippets.

@fexx
Last active July 31, 2020 21:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fexx/4694d4608dea0fb20edc9b8ae26ab8c9 to your computer and use it in GitHub Desktop.
Save fexx/4694d4608dea0fb20edc9b8ae26ab8c9 to your computer and use it in GitHub Desktop.
Arquivo car.service.ts (Consumindo API REST com HttpClient no Angular 8)
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { Car } from '../models/car';
@Injectable({
providedIn: 'root'
})
export class CarService {
url = 'http://localhost:3000/cars'; // api rest fake
// injetando o HttpClient
constructor(private httpClient: HttpClient) { }
// Headers
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}
// Obtem todos os carros
getCars(): Observable<Car[]> {
return this.httpClient.get<Car[]>(this.url)
.pipe(
retry(2),
catchError(this.handleError))
}
// Obtem um carro pelo id
getCarById(id: number): Observable<Car> {
return this.httpClient.get<Car>(this.url + '/' + id)
.pipe(
retry(2),
catchError(this.handleError)
)
}
// salva um carro
saveCar(car: Car): Observable<Car> {
return this.httpClient.post<Car>(this.url, JSON.stringify(car), this.httpOptions)
.pipe(
retry(2),
catchError(this.handleError)
)
}
// utualiza um carro
updateCar(car: Car): Observable<Car> {
return this.httpClient.put<Car>(this.url + '/' + car.id, JSON.stringify(car), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
)
}
// deleta um carro
deleteCar(car: Car) {
return this.httpClient.delete<Car>(this.url + '/' + car.id, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
)
}
// Manipulação de erros
handleError(error: HttpErrorResponse) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// Erro ocorreu no lado do client
errorMessage = error.error.message;
} else {
// Erro ocorreu no lado do servidor
errorMessage = `Código do erro: ${error.status}, ` + `menssagem: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment