X-Git-Url: https://juplo.de/gitweb/?a=blobdiff_plain;f=src%2Fapp%2Fhero.service.ts;h=6df713db1826ca67060f377bc78cd97e373fd973;hb=3efe152e8e2be6f2dc172cf1ac476e2cb01be54b;hp=f8374b1d8213f486e2fcd17edb016be04620a0c2;hpb=a74bb0fa3f25f033319a4987bbec1acdc548f3dc;p=examples%2Fangular-tour-of-heroes diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index f8374b1..6df713d 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -12,7 +12,10 @@ import { catchError, tap } from 'rxjs/operators'; }) export class HeroService { - private heroesUrl = 'api/heroes'; // URL to web api + heroesUrl = 'api/heroes'; // URL to web api + httpOptions = { + headers: new HttpHeaders({ 'Content-Type': 'application/json' }) + }; constructor( private http: HttpClient, @@ -28,14 +31,22 @@ 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}`)) + ); + } + + /** PUT: update the hero on the server */ + updateHero(hero: Hero): Observable { + return this.http.put(this.heroesUrl, hero, this.httpOptions).pipe( + tap(_ => this.log(`updated hero id=${hero.id}`)), + catchError(this.handleError('updateHero')) + ); } /** @@ -54,7 +65,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); + } }; }