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

时间:2022-07-23
本文章向大家介绍使用Angular HTTP client对数据模型进行update操作,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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