且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Angular HTTP client对数据模型进行update操作

更新时间:2022-09-09 16:29:58

需求:在hero列表里点击某个hero,进入明细页面:使用Angular HTTP client对数据模型进行update操作

在明细页面里修改hero name,点击save后,再回到hero列表,期望detail页面做的修改能够持久化。

使用Angular HTTP client对数据模型进行update操作

下面是具体做法:

(1) hero detail Component的html里,新增一个按钮,绑定click事件的处理函数为save:

使用Angular HTTP client对数据模型进行update操作

detail Component的hero属性,需要加上@Input annotation:使用Angular HTTP client对数据模型进行update操作

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

使用Angular HTTP client对数据模型进行update操作

httpOptions的值:使用Angular HTTP client对数据模型进行update操作

httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };