X-Git-Url: https://juplo.de/gitweb/?a=blobdiff_plain;f=src%2Fapp%2Fhero.service.ts;h=f8374b1d8213f486e2fcd17edb016be04620a0c2;hb=a74bb0fa3f25f033319a4987bbec1acdc548f3dc;hp=649b856d72174286f9b026a9ead013311b8acb42;hpb=fd92a662c471619278e561f25a4beb7ef78d0690;p=examples%2Fangular-tour-of-heroes diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index 649b856..f8374b1 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -2,7 +2,9 @@ import { Injectable } from '@angular/core'; import { Observable, of, EMPTY } from 'rxjs'; import { Hero } from './hero'; import { HEROES } from './mock-heroes'; +import { HttpClient, HttpHeaders } from '@angular/common/http'; import { MessageService } from './message.service'; +import { catchError, tap } from 'rxjs/operators'; @Injectable({ @@ -10,15 +12,24 @@ import { MessageService } from './message.service'; }) export class HeroService { - constructor(private messageService : MessageService) { } + private heroesUrl = 'api/heroes'; // URL to web api - getHeroes() : Observable { - this.messageService.add('HeroService: fetching heroes...'); - return of(HEROES); + constructor( + private http: HttpClient, + private messageService: MessageService) { } + + getHeroes(): Observable { + this.log('fetching heroes...'); + return this.http + .get(this.heroesUrl) + .pipe( + tap((heroes: Hero[]) => this.log(`fetched ${heroes.length} heroes`)), + catchError(this.handleError('getHeroes', [])) + ); } getHero(id: number): Observable { - this.messageService.add(`HeroService: requested hero id=${id}`); + this.log(`requested hero id=${id}`); const found: Hero | undefined = HEROES.find(hero => hero.id === id); if (found === undefined) { return EMPTY; @@ -26,4 +37,29 @@ export class HeroService { return of(found); } } + + /** + * 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}`); + } }