61 lines
2.1 KiB
TypeScript
61 lines
2.1 KiB
TypeScript
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
|
|
import { Injectable } from '@angular/core';
|
|
import { Observable } from 'rxjs/internal/Observable';
|
|
import { catchError } from 'rxjs/operators';
|
|
|
|
import { ErrorLoggerService } from '../core/error-logger.service';
|
|
import { Product } from '../core/product';
|
|
|
|
const url = '/api/products';
|
|
const serviceName = 'ProductService';
|
|
|
|
@Injectable({ providedIn: 'root' })
|
|
export class ProductService {
|
|
constructor(private http: HttpClient, private log: ErrorLoggerService) {}
|
|
|
|
get(id: string | null): Observable<Product> {
|
|
const getUrl: string = id === null ? `${url}` : `${url}/${id}`;
|
|
return this.http
|
|
.get<Product>(getUrl)
|
|
.pipe(catchError(this.log.handleError(serviceName, `get id as Observable<Product>=${id}`))) as Observable<Product>;
|
|
}
|
|
|
|
list(): Observable<Product[]> {
|
|
return this.http
|
|
.get<Product[]>(`${url}/list`)
|
|
.pipe(catchError(this.log.handleError(serviceName, 'getList'))) as Observable<Product[]>;
|
|
}
|
|
|
|
save(product: Product): Observable<Product> {
|
|
return this.http
|
|
.post<Product>(`${url}`, product)
|
|
.pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable<Product>;
|
|
}
|
|
|
|
update(product: Product): Observable<Product> {
|
|
return this.http
|
|
.put<Product>(`${url}/${product.id}`, product)
|
|
.pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable<Product>;
|
|
}
|
|
|
|
saveOrUpdate(product: Product): Observable<Product> {
|
|
if (!product.id) {
|
|
return this.save(product);
|
|
}
|
|
return this.update(product);
|
|
}
|
|
|
|
delete(id: string): Observable<Product> {
|
|
return this.http
|
|
.delete<Product>(`${url}/${id}`)
|
|
.pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable<Product>;
|
|
}
|
|
|
|
autocomplete(query: string): Observable<Product[]> {
|
|
const options = { params: new HttpParams().set('q', query) };
|
|
return this.http
|
|
.get<Product[]>(`${url}/query`, options)
|
|
.pipe(catchError(this.log.handleError(serviceName, 'autocomplete'))) as Observable<Product[]>;
|
|
}
|
|
}
|