import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/internal/Observable'; import { catchError } from 'rxjs/operators'; import { Customer } from '../core/customer'; import { ErrorLoggerService } from '../core/error-logger.service'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), }; const url = '/api/customers'; const serviceName = 'CustomerService'; @Injectable({ providedIn: 'root', }) export class CustomerService { constructor(private http: HttpClient, private log: 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(): Observable { return this.http .get(`${url}/list`) .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; } }