需求:在hero列表里点击某个hero,进入明细页面:
在明细页面里修改hero name,点击save后,再回到hero列表,期望detail页面做的修改能够持久化。
下面是具体做法:
(1) hero detail Component的html里,新增一个按钮,绑定click事件的处理函数为save:
detail Component的hero属性,需要加上@Input annotation:
save函数的实现:
save(): void {
this.heroService.updateHero(this.hero)
.subscribe(() => this.goBack());
}
具体的保存,是转交给Hero service实现。
(2) hero service里updateHero函数的实现:
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'))
);
}
httpOptions的值:
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
要获取更多Jerry的原创文章,请关注公众号"汪子熙":