58 lines
1.8 KiB
TypeScript
58 lines
1.8 KiB
TypeScript
import { HttpClient, HttpHeaders, httpResource, HttpResourceRef } from '@angular/common/http';
|
|
import { Injectable, Signal, inject } from '@angular/core';
|
|
import { Observable } from 'rxjs';
|
|
import { catchError } from 'rxjs/operators';
|
|
|
|
import { ErrorLoggerService } from '../core/error-logger.service';
|
|
import { Printer } from '../core/printer';
|
|
|
|
const httpOptions = {
|
|
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
|
|
};
|
|
const url = '/api/printers';
|
|
const serviceName = 'PrinterService';
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class PrinterService {
|
|
private http = inject(HttpClient);
|
|
private log = inject(ErrorLoggerService);
|
|
|
|
get(id: Signal<string | null>): HttpResourceRef<Printer | undefined> {
|
|
return httpResource<Printer>(() => {
|
|
const idVal = id();
|
|
return idVal === null || idVal === undefined ? url : `${url}/${idVal}`;
|
|
});
|
|
}
|
|
|
|
list(): HttpResourceRef<Printer[] | undefined> {
|
|
return httpResource<Printer[]>(() => `${url}/list`);
|
|
}
|
|
|
|
save(printer: Printer): Observable<Printer> {
|
|
return this.http
|
|
.post<Printer>(url, printer, httpOptions)
|
|
.pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable<Printer>;
|
|
}
|
|
|
|
update(printer: Printer): Observable<Printer> {
|
|
return this.http
|
|
.put<Printer>(`${url}/${printer.id}`, printer, httpOptions)
|
|
.pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable<Printer>;
|
|
}
|
|
|
|
saveOrUpdate(printer: Printer): Observable<Printer> {
|
|
if (!printer.id) {
|
|
return this.save(printer);
|
|
}
|
|
return this.update(printer);
|
|
}
|
|
|
|
delete(id: string): Observable<Printer> {
|
|
return this.http
|
|
.delete<Printer>(`${url}/${id}`, httpOptions)
|
|
.pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable<Printer>;
|
|
}
|
|
}
|