add Add a new hero
This commit is contained in:
parent
8168d2023c
commit
973524fc7e
|
@ -48,6 +48,14 @@ export class HeroService {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 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'))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle Http operation that failed.
|
* Handle Http operation that failed.
|
||||||
* Let the app continue.
|
* Let the app continue.
|
||||||
|
|
|
@ -6,3 +6,13 @@
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label for="new-hero">Hero name: </label>
|
||||||
|
<input id="new-hero" #heroName />
|
||||||
|
|
||||||
|
<!-- (click) passes input value to add() and then clears the input -->
|
||||||
|
<button type="button" class="add-button" (click)="add(heroName.value); heroName.value=''">
|
||||||
|
Add hero
|
||||||
|
</button>
|
||||||
|
</div>
|
|
@ -29,4 +29,14 @@ export class HeroesComponent implements OnInit {
|
||||||
this.heroService.getHeroes()
|
this.heroService.getHeroes()
|
||||||
.subscribe(heroes => this.heroes = heroes);
|
.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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
Loading…
Reference in New Issue