1 通过 id 获取英雄, 暴露 getHero(id: number): Observable<Hero>
返回可观察对象 Hero
, 可以看到,不同的地方在于获取的地址变成了 ${this.heroesUrl}/${id}
src/app/hero.service.ts
/** GET hero by id. Will 404 if id not found */
getHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`;
return this.http.get<Hero>(url).pipe(
tap(_ => this.log(`fetched hero id=${id}`)),
catchError(this.handleError<Hero>(`getHero id=${id}`))
);
}
2 修改英雄
- 2.1 在
hero-detail.component.html
模板底部增加保存按钮
src/app/hero-detail/hero-detail.component.html
<button (click)="save()">save</button>
src/app/hero-detail/hero-detail.component.ts
save(): void {
this.heroService.updateHero(this.hero)
.subscribe(() => this.goBack());
}
src/app/hero.service.ts
/** PUT: update the hero on the server */
updateHero(hero: Hero): Observable<any> {
return this.http.put(this.heroesUrl, hero, this.httpOptions).pipe(
tap(_ => this.log(`updated hero id=${hero.id}`)),
catchError(this.handleError<any>('updateHero'))
);
}
HttpClient.put() 方法接受三个参数:
URL 地址
要修改的数据(这里就是修改后的英雄)
选项
- 2.4 增加Options, 其实就是定义格式为json
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
3 添加新英雄
src/app/heroes/heroes.component.html
<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>
src/app/heroes/heroes.component.ts
add(name: string): void {
name = name.trim();
if (!name) { return; }
this.heroService.addHero({ name } as Hero)
.subscribe(hero => {
this.heroes.push(hero);
});
}
src/app/heroes/heroes.component.ts
/** 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'))
);
}
4 删除英雄
- 4.1 修改模板, 在每个循环的li后面增加一个删除按钮
src/app/heroes/heroes.component.html
<ul class="heroes">
<li *ngFor="let hero of heroes">
<a routerLink="/detail/{{hero.id}}">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</a>
<button class="delete" title="delete hero"
(click)="delete(hero)">x</button>
</li>
</ul>
- 4.2 增加模板的删除事件, 这里有两个事情, 1是将英雄筛选,不包含当前删除的英雄, 二是从服务中删除掉这个英雄. 可以看出,这里是先处理前端再处理后端的,原因是后端可能要时间,也有可能返回失败
src/app/heroes/heroes.component.ts
delete(hero: Hero): void {
this.heroes = this.heroes.filter(h => h !== hero);
this.heroService.deleteHero(hero).subscribe();
}
- 4.3 修改对应的HeroService方法, 这里也是提交到对应的
${this.heroesUrl}/${id}
src/app/hero.service.ts
/** DELETE: delete the hero from the server */
deleteHero(hero: Hero | number): Observable<Hero> {
const id = typeof hero === 'number' ? hero : hero.id;
const url = `${this.heroesUrl}/${id}`;
return this.http.delete<Hero>(url, this.httpOptions).pipe(
tap(_ => this.log(`deleted hero id=${id}`)),
catchError(this.handleError<Hero>('deleteHero'))
);
}