HttpClient est le service intégré d'Angular pour effectuer des requêtes HTTP (GET, POST, DELETE, PUT). Il permet de communiquer avec des API REST, récupérer des données JSON, gérer les erreurs, et bien plus encore.
Pour utiliser le HttpClient, vous devez ajouter provideHttpClient() dans le tableau de providers de app.config.ts.
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
};import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class ProductService {
private apiUrl = 'https://dummyjson.com/products';
constructor(private http: HttpClient) {}
getProducts(): Observable<any> {
return this.http.get<any>(this.apiUrl).pipe(catchError(this.handleError));
}
getProductById(id: number): Observable<any> {
return this.http.get<any>(`${this.apiUrl}/${id}`).pipe(catchError(this.handleError));
}
addProduct(product: any): Observable<any> {
return this.http.post<any>(this.apiUrl, product, this.httpOptions()).pipe(catchError(this.handleError));
}
updateProduct(id: number, product: any): Observable<any> {
return this.http.put<any>(`${this.apiUrl}/${id}`, product, this.httpOptions()).pipe(catchError(this.handleError));
}
deleteProduct(id: number): Observable<any> {
return this.http.delete<any>(`${this.apiUrl}/${id}`).pipe(catchError(this.handleError));
}
private handleError(error: any) {
console.error('Erreur détectée:', error);
return throwError(() => new Error('Problème avec l\'API.'));
}
private httpOptions() {
return {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
}
}import { Component, OnInit } from '@angular/core';
import { ProductService } from '../services/product.service';
@Component({
selector: 'app-product',
template: `
<div class="container">
<h1>Liste des Produits</h1>
@if (hasError) {
<p class="text-danger">Erreur de chargement.</p>
}
@if (products.length > 0) {
<div class="row">
@for (product of products; track product.id) {
<div class="col-md-4">
<h5>{{ product.title }}</h5>
</div>
}
</div>
}
</div>
`
})
export class ProductComponent implements OnInit {
products: any[] = [];
hasError: boolean = false;
constructor(private productService: ProductService) {}
ngOnInit(): void {
this.productService.getProducts().subscribe({
next: (response) => {
this.products = response.products;
},
error: (err) => {
this.hasError = true;
}
});
}
}