X-Git-Url: https://juplo.de/gitweb/?a=blobdiff_plain;f=src%2Fapp%2Fhero.service.ts;h=75a002b12d73f9bd7180590dfd9835b254ac8bc9;hb=806998ac75abe1082f666c141e0bd3f1a8ae7af1;hp=9003fe1fb02718907bde31a3bfc4eb3bac35c734;hpb=f18faff7c576b595dd8765f36805aa8176122db7;p=examples%2Fangular-tour-of-heroes diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index 9003fe1..75a002b 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -1,8 +1,10 @@ import { Injectable } from '@angular/core'; -import { Observable, of } from 'rxjs'; +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,58 @@ import { MessageService } from './message.service'; }) export class HeroService { - constructor(private messageService : MessageService) { } + 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', [])) + ); } + /** GET hero by id. Will 404 if id not found */ getHero(id: number): Observable { - this.messageService.add(`HeroService: fetched hero id=${id}`); - return of(HEROES.find(hero => hero.id === id)); + this.log(`requested hero id=${id}`); + const url = `${this.heroesUrl}/${id}`; + return this.http.get(url).pipe( + tap(_ => this.log(`fetched hero id=${id}`)), + catchError(this.handleError(`getHero id=${id}`)) + ); + } + + /** + * 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. + if (result === undefined) { + return EMPTY as Observable; + } else { + return of(result as T); + } + }; + } + + /** Log a HeroService message with the MessageService */ + private log(message: string) { + this.messageService.add(`HeroService: ${message}`); } }