From cbadc2c63fa11dc938469117ec8f4a65a7873851 Mon Sep 17 00:00:00 2001 From: Kai Moritz Date: Sat, 16 May 2020 13:53:43 +0200 Subject: [PATCH] 6: Get Data from a Server g) Heroes and HTTP - Get hero by id --- src/app/hero.service.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index f8374b1..a0b5d5b 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -28,14 +28,14 @@ export class HeroService { ); } + /** GET hero by id. Will 404 if id not found */ 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); - } + const url = `${this.heroesUrl}/${id}`; + return this.http.get(url).pipe( + tap(_ => this.log(`fetched hero id=${id}`)), + catchError(this.handleError(`getHero id=${id}`)) + ); } /** @@ -54,7 +54,11 @@ export class HeroService { this.log(`${operation} failed: ${error.message}`); // Let the app keep running by returning an empty result. - return of(result as T); + if (result === undefined) { + return EMPTY as Observable; + } else { + return of(result as T); + } }; } -- 2.20.1