更新时间:2022-09-09 16:34:44
需求:在Hero列表里增添创建hero的UI,点击Add按钮之后,可以创建新的
实现步骤:
(1) 在hero Component上绘制用于新建hero的UI:
<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>
add函数的实现:
add(name: string): void { name = name.trim(); if (!name) { return; } this.heroService.addHero({ name } as Hero) .subscribe(hero => { this.heroes.push(hero); }); }
(2) 实现Hero Service的addHero函数:
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')) ); }
: