From: Kai Moritz Date: Sat, 16 May 2020 11:53:43 +0000 (+0200) Subject: 6: Get Data from a Server X-Git-Url: http://juplo.de/gitweb/?a=commitdiff_plain;h=cbadc2c63fa11dc938469117ec8f4a65a7873851;p=examples%2Fangular-tour-of-heroes 6: Get Data from a Server g) Heroes and HTTP - Get hero by id --- 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); + } }; }