Angular
Angular Services

📌 C'est quoi HttpClient ?

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.

Configuration

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;
      }
    });
  }
}

Démonstration : Liste des Produits

9 résultats
Essence Mascara Lash Princess beauty
Essence Mascara Lash Princess

The Essence Mascara Lash Princess is a popular mascara known for its volumizing and lengthening effects. Achieve dramatic lashes with this long-lasting and cruelty-free formula.

9.99 €
Eyeshadow Palette with Mirror beauty
Eyeshadow Palette with Mirror

The Eyeshadow Palette with Mirror offers a versatile range of eyeshadow shades for creating stunning eye looks. With a built-in mirror, it's convenient for on-the-go makeup application.

19.99 €
Powder Canister beauty
Powder Canister

The Powder Canister is a finely milled setting powder designed to set makeup and control shine. With a lightweight and translucent formula, it provides a smooth and matte finish.

14.99 €
Red Lipstick beauty
Red Lipstick

The Red Lipstick is a classic and bold choice for adding a pop of color to your lips. With a creamy and pigmented formula, it provides a vibrant and long-lasting finish.

12.99 €
Red Nail Polish beauty
Red Nail Polish

The Red Nail Polish offers a rich and glossy red hue for vibrant and polished nails. With a quick-drying formula, it provides a salon-quality finish at home.

8.99 €
Calvin Klein CK One fragrances
Calvin Klein CK One

CK One by Calvin Klein is a classic unisex fragrance, known for its fresh and clean scent. It's a versatile fragrance suitable for everyday wear.

49.99 €
Chanel Coco Noir Eau De fragrances
Chanel Coco Noir Eau De

Coco Noir by Chanel is an elegant and mysterious fragrance, featuring notes of grapefruit, rose, and sandalwood. Perfect for evening occasions.

129.99 €
Dior J'adore fragrances
Dior J'adore

J'adore by Dior is a luxurious and floral fragrance, known for its blend of ylang-ylang, rose, and jasmine. It embodies femininity and sophistication.

89.99 €
Dolce Shine Eau de fragrances
Dolce Shine Eau de

Dolce Shine by Dolce & Gabbana is a vibrant and fruity fragrance, featuring notes of mango, jasmine, and blonde woods. It's a joyful and youthful scent.

69.99 €