需求:在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' })
};