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)
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter