X-Git-Url: https://juplo.de/gitweb/?a=blobdiff_plain;f=src%2Fapp%2Fhero.service.ts;h=90fa42c4eafc17eea7cebd39385df345a8e7e3ff;hb=10071c9e2d5fefe91c5b8d9946bb964776b59c0e;hp=d0801f302c28fedf0cd9c61e92addb21569b27ef;hpb=cdbcd5578c991169816c9b621c5a571ffdaefeb8;p=examples%2Fangular-tour-of-heroes diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index d0801f3..90fa42c 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 } from 'rxjs/operators'; @Injectable({ @@ -10,9 +12,53 @@ import { MessageService } from './message.service'; }) export class HeroService { - constructor(private messageService : MessageService) { } + private heroesUrl = 'api/heroes'; // URL to web api - getHeroes() : Observable { - return of(HEROES); + constructor( + private http: HttpClient, + private messageService: MessageService) { } + + getHeroes(): Observable { + this.log('fetching heroes...'); + return this.http + .get(this.heroesUrl) + .pipe( + catchError(this.handleError('getHeroes', [])) + ); + } + + getHero(id: number): Observable { + this.log(`requested hero id=${id}`); + const found: Hero | undefined = HEROES.find(hero => hero.id === id); + if (found === undefined) { + return EMPTY; + } else { + 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}`); } }