import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http'; import {ErrorLoggerService} from '../core/error-logger.service'; import {catchError} from 'rxjs/operators'; import {Observable} from 'rxjs/internal/Observable'; import {User} from './user'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const url = '/v1/users'; const serviceName = 'UserService'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http: HttpClient, private log: ErrorLoggerService) { } get(id: string): Observable { const getUrl: string = (id === null) ? `${url}/new` : `${url}/${id}`; return >this.http.get(getUrl) .pipe( catchError(this.log.handleError(serviceName, `get id=${id}`)) ); } list(): Observable { const options = {params: new HttpParams().set('l', '')}; return >this.http.get(`${url}/list`, options) .pipe( catchError(this.log.handleError(serviceName, 'list')) ); } listOfNames(): Observable { const options = {params: new HttpParams().set('n', '')}; return >this.http.get(`${url}/list`, options) .pipe( catchError(this.log.handleError(serviceName, 'list')) ); } save(user: User): Observable { return >this.http.put(`${url}/new`, user, httpOptions) .pipe( catchError(this.log.handleError(serviceName, 'save')) ); } update(user: User): Observable { return >this.http.post(`${url}/${user.id}`, user, httpOptions) .pipe( catchError(this.log.handleError(serviceName, 'update')) ); } saveOrUpdate(user: User): Observable { if (!user.id) { return this.save(user); } else { return this.update(user); } } delete(id: string): Observable { return >this.http.delete(`${url}/${id}`, httpOptions) .pipe( catchError(this.log.handleError(serviceName, 'delete')) ); } }