0

我目前正在使用英雄的角度之旅来学习角度。我通过以下示例稍微了解了这些概念。我现在正在添加一个新英雄。对于那些完成教程的人,我只是有疑问。

在添加英雄中,我无法理解它。你能帮我理解一下这个addHero()方法是如何在服务器上添加新英雄的吗?我期待一种可以做到这一点的方法。但我没有看到任何添加方法。

我来自 PHP/JS,jQuery 背景。所以我期待这样的事情

  1. addHero()hero.component.ts 中的方法
  2. addHero()hero.service.ts 中的方法
  3. 来自 PHP MVC,addHero()模型中的方法将更新数据库中的数据。

希望你能容忍我,我想在继续下一步之前了解它是如何工作的。

谢谢大家。

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/hero.service.ts (addHero)

/** 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

1 回答 1

0
  name = name.trim();
  if (!name) { return; }
  this.heroService.addHero({ name } as Hero)
    .subscribe(hero => {
      this.heroes.push(hero);
    });
}```

Inside ts file, add function is called with name as param. The spaces on the sides are trimmed, again checked if there is a valid namestring. If not, it will not proceed. If there is one, a service will be called, with the name param passed and is subscribed. After subscription, if there is a response, the reponse will be pushed to this.heroes.

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

addHero service calls the api and pass the name which was sent from ts to the api and if there is a correct response, this.log() is called. If there is an error, it is caught.

For more info about tap and pipe, go through rxjs docs.
于 2021-08-13T03:58:20.200 回答