);
}
+ /** POST: add a new hero to the server */
+ addHero(hero: Hero): Observable<Hero> {
+ return this.http.post<Hero>(this.heroesUrl, hero, this.httpOptions).pipe(
+ tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)),
+ catchError(this.handleError<Hero>('addHero'))
+ );
+ }
+
/** GET hero by id. Will 404 if id not found */
getHero(id: number): Observable<Hero> {
this.log(`requested hero id=${id}`);
<h2>My Heroes</h2>
+<div>
+ <label>Hero name:
+ <input #heroName />
+ </label>
+ <!-- (click) passes input value to add() and then clears the input -->
+ <button (click)="add(heroName.value); heroName.value=''">
+ add
+ </button>
+</div>
<ul class="heroes">
<li *ngFor="let hero of heroes">
<a routerLink="/detail/{{hero.id}}">
.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
+
+ add(name: string): void {
+ name = name.trim();
+ if (!name) { return; }
+ this.heroService.addHero({ name } as Hero)
+ .subscribe(hero => {
+ this.heroes.push(hero);
+ });
+ }
}