add Add a new hero

This commit is contained in:
Костя 2025-06-24 12:58:13 +03:00
parent 8168d2023c
commit 973524fc7e
3 changed files with 29 additions and 1 deletions

View File

@ -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.

View File

@ -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>

View File

@ -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);
});
}
} }