service exemplo

PHOTO EMBED

Sun Jan 22 2023 00:14:43 GMT+0000 (Coordinated Universal Time)

Saved by @ilivanilton #angular #rxjs-pattern

import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpClient } from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { catchError, shareReplay } from 'rxjs/operators';

import { Product } from './models/product.model';

@Injectable({
  providedIn: 'root'
})
export class ProductsService {
  private const API = 'api/products';

  allProducts$ = this.http.get<Product[]>(this.API).pipe(
    shareReplay(1),
    catchError(this.handleError),
    );

  constructor(private http: HttpClient){}

  private handleError(err: HttpErrorResponse): Observable<never>{
    let errorMessage: string;
    if(err.error instanceof ErrorEvent){
      errorMessage = `Um error ocorreu: ${err.error.message}`;
    }else{
      errorMessage = `Servidor retornou codigo ${err.status}: ${err.message}`;
    }
    console.warn(err);
    return throwError(() => errorMessage)
  }

}
content_copyCOPY