diff --git a/src/app/error-handling.service.spec.ts b/src/app/error-handling.service.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..d715334f83b7ce091a8232384431509003e1b494 --- /dev/null +++ b/src/app/error-handling.service.spec.ts @@ -0,0 +1,15 @@ +import { TestBed, inject } from '@angular/core/testing'; + +import { ErrorHandlingService } from './error-handling.service'; + +describe('ErrorHandlingService', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ErrorHandlingService] + }); + }); + + it('should be created', inject([ErrorHandlingService], (service: ErrorHandlingService) => { + expect(service).toBeTruthy(); + })); +}); diff --git a/src/app/error-handling.service.ts b/src/app/error-handling.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..88a6f38aa858bd3cc0885cc355a686ac0105f18d --- /dev/null +++ b/src/app/error-handling.service.ts @@ -0,0 +1,17 @@ +import { Injectable } from '@angular/core'; +import { Observable } from 'rxjs/Observable'; +import { of } from 'rxjs/observable/of'; + +@Injectable() +export class ErrorHandlingService { + + constructor() { + } + + public handleError<T>(operation = 'operation', result?: T) { + return (error: any): Observable<T> => { + console.error(error); + return of(result as T); + }; + } +} diff --git a/src/app/room.service.ts b/src/app/room.service.ts index f0d336c2b853c4823c36ef404bf045e7b9839fdf..32a438e6976d358e679dfc60d4ff9f352ce9030e 100644 --- a/src/app/room.service.ts +++ b/src/app/room.service.ts @@ -2,28 +2,40 @@ import { Injectable } from '@angular/core'; import { Room } from './room'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; +import { catchError, tap } from 'rxjs/operators'; +import { ErrorHandlingService } from './error-handling.service'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable() -export class RoomService { +export class RoomService extends ErrorHandlingService { private roomsUrl = 'api/rooms'; constructor(private http: HttpClient) { + super(); } getRooms(): Observable<Room[]> { - return this.http.get<Room[]>(this.roomsUrl); + return this.http.get<Room[]>(this.roomsUrl).pipe( + tap (_ => ''), + catchError(this.handleError('getRooms', [])) + ); } addRoom(room: Room): Observable<Room> { - return this.http.post<Room>(this.roomsUrl, room, httpOptions); + return this.http.post<Room>(this.roomsUrl, room, httpOptions).pipe( + tap (_ => ''), + catchError(this.handleError<Room>('addRoom')) + ); } getRoom(id: string): Observable<Room> { const url = `${this.roomsUrl}/${id}`; - return this.http.get<Room>(url); + return this.http.get<Room>(url).pipe( + tap (_ => ''), + catchError(this.handleError<Room>(`getRoom id=${id}`)) + ); } }