X-Git-Url: https://juplo.de/gitweb/?p=examples%2Fangular-tour-of-heroes;a=blobdiff_plain;f=src%2Fapp%2Fhero.service.ts;fp=src%2Fapp%2Fhero.service.ts;h=90fa42c4eafc17eea7cebd39385df345a8e7e3ff;hp=d44f22ff21f99ce70f1b52c72b04c5330b2f8911;hb=10071c9e2d5fefe91c5b8d9946bb964776b59c0e;hpb=b52b79a39e71932d1413cfbeca4d4ae3a50fe35b diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index d44f22f..90fa42c 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -2,8 +2,9 @@ import { Injectable } from '@angular/core'; import { Observable, of, EMPTY } from 'rxjs'; import { Hero } from './hero'; import { HEROES } from './mock-heroes'; -import { HttpClient } from '@angular/common/http'; +import { HttpClient, HttpHeaders } from '@angular/common/http'; import { MessageService } from './message.service'; +import { catchError } from 'rxjs/operators'; @Injectable({ @@ -19,7 +20,11 @@ export class HeroService { getHeroes(): Observable { this.log('fetching heroes...'); - return this.http.get(this.heroesUrl); + return this.http + .get(this.heroesUrl) + .pipe( + catchError(this.handleError('getHeroes', [])) + ); } getHero(id: number): Observable { @@ -32,6 +37,26 @@ export class HeroService { } } + /** + * Handle Http operation that failed. + * Let the app continue. + * @param operation - name of the operation that failed + * @param result - optional value to return as the observable result + */ + private handleError(operation = 'operation', result?: T) { + return (error: any): Observable => { + + // TODO: send the error to remote logging infrastructure + console.error(error); // log to console instead + + // TODO: better job of transforming error for user consumption + this.log(`${operation} failed: ${error.message}`); + + // Let the app keep running by returning an empty result. + return of(result as T); + }; + } + /** Log a HeroService message with the MessageService */ private log(message: string) { this.messageService.add(`HeroService: ${message}`);