X-Git-Url: https://juplo.de/gitweb/?a=blobdiff_plain;f=src%2Fapp%2Fhero.service.ts;h=349d043a10ee94158ddb3260ea18c6227f8329cc;hb=5c525c7b08b4ea57e94f1c8644297de8e443e2da;hp=90fa42c4eafc17eea7cebd39385df345a8e7e3ff;hpb=10071c9e2d5fefe91c5b8d9946bb964776b59c0e;p=examples%2Fangular-tour-of-heroes diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index 90fa42c..349d043 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -4,7 +4,7 @@ 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'; +import { catchError, tap } from 'rxjs/operators'; @Injectable({ @@ -12,7 +12,10 @@ import { catchError } 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, @@ -23,18 +26,35 @@ export class HeroService { return this.http .get(this.heroesUrl) .pipe( + tap((heroes: Hero[]) => this.log(`fetched ${heroes.length} heroes`)), catchError(this.handleError('getHeroes', [])) ); } + /** POST: add a new hero to the server */ + addHero(hero: Hero): Observable { + return this.http.post(this.heroesUrl, hero, this.httpOptions).pipe( + tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)), + catchError(this.handleError('addHero')) + ); + } + + /** 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')) + ); } /** @@ -53,7 +73,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); + } }; }