51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
import { Injectable } from "@angular/core";
|
|
import { Hotel } from "../hotel-item/hotel";
|
|
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
|
|
import { Observable, throwError, catchError } from "rxjs";
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class HotelService {
|
|
private apiUrl = 'api/hotels';
|
|
|
|
constructor(private http: HttpClient) {}
|
|
|
|
private handleError(error: HttpErrorResponse) {
|
|
let errorMessage = 'An error occurred';
|
|
if (error.error instanceof ErrorEvent) {
|
|
// Client-side error
|
|
errorMessage = `Error: ${error.error.message}`;
|
|
} else {
|
|
// Server-side error
|
|
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
|
|
}
|
|
console.error(errorMessage);
|
|
return throwError(() => errorMessage);
|
|
}
|
|
|
|
public getHotels(): Observable<Hotel[]> {
|
|
return this.http.get<Hotel[]>(this.apiUrl)
|
|
.pipe(catchError(this.handleError));
|
|
}
|
|
|
|
public getHotel(id: number): Observable<Hotel> {
|
|
return this.http.get<Hotel>(`${this.apiUrl}/${id}`)
|
|
.pipe(catchError(this.handleError));
|
|
}
|
|
|
|
public createHotel(hotel: Hotel): Observable<Hotel> {
|
|
return this.http.post<Hotel>(this.apiUrl, hotel)
|
|
.pipe(catchError(this.handleError));
|
|
}
|
|
|
|
public updateHotel(hotel: Hotel): Observable<Hotel> {
|
|
return this.http.put<Hotel>(`${this.apiUrl}/${hotel.id}`, hotel)
|
|
.pipe(catchError(this.handleError));
|
|
}
|
|
|
|
public deleteHotel(id: number): Observable<{}> {
|
|
return this.http.delete(`${this.apiUrl}/${id}`)
|
|
.pipe(catchError(this.handleError));
|
|
}
|
|
}
|