import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { Injectable, inject } from '@angular/core'; import { Observable } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { Customer } from '../core/customer'; import { ErrorLoggerService } from '../core/error-logger.service'; import { PagedResult } from '../core/paged-result'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), }; const url = '/api/customers'; const serviceName = 'CustomerService'; @Injectable({ providedIn: 'root', }) export class CustomerService { private http = inject(HttpClient); private log = inject(ErrorLoggerService); get(id: string | null): Observable { const getUrl: string = id === null ? `${url}` : `${url}/${id}`; return this.http .get(getUrl) .pipe(catchError(this.log.handleError(serviceName, `get id=${id}`))) as Observable; } list(q: string | null, page = 0, size = 50, field = 'name', direction = 'asc'): Observable> { const params = { ...(q ? { q } : {}), p: page, s: size, f: field, d: direction, }; console.log('CustomerService.list', params); return this.http .get>(`${url}/list`, { params }) .pipe(catchError(this.log.handleError(serviceName, 'list'))) as Observable>; } save(customer: Customer): Observable { return this.http .post(`${url}`, customer, httpOptions) .pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable; } update(customer: Customer): Observable { return this.http .put(`${url}/${customer.id}`, customer, httpOptions) .pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable; } saveOrUpdate(customer: Customer): Observable { if (!customer.id) { return this.save(customer); } return this.update(customer); } delete(id: string): Observable { return this.http .delete(`${url}/${id}`, httpOptions) .pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable; } autocomplete(query: string): Observable { const options = { params: new HttpParams().set('q', query) }; return this.http .get(`${url}/query`, options) .pipe(catchError(this.log.handleError(serviceName, 'autocomplete'))) as Observable; } }