【问题标题】:Angular Tour of HeroesAngular 英雄之旅
【发布时间】:2021-08-13 11:58:20
【问题描述】:

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

在添加英雄中,我无法理解它。你能帮我理解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'))
  );
}

【问题讨论】:

  • 您可能想阅读更多关于可观察(也称为反应式编程)的内容。理解它的最简单方法是阅读rxjs Observable 就像一个具有附加功能的lazy 数组。它只会在您订阅时运行。
  • rxviz.com 看看这个,它可能会帮助你了解pipetapsubscribe是什么
  • Angular 指南介绍了 observables:angular.io/guide/observables-in-angular - 我认为 Stack Overflow 上没有人会写一个不同的教程。它肯定与你描述的方式非常不同(尽管有一整本书是关于 PHP 反应式编程的)
  • 谢谢大家!所以要理解它,我需要先理解 Observables。感谢您为我指明正确的方向。

标签: angular angular-tour-of-heroes


【解决方案1】:
  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.

【讨论】:

  • 嗨!根据您的解释,我可以说 API(this.heroesUrl) 在其中包含将英雄添加到数据库/json 对象的 add 方法/代码吗?
  • this.heroesUrl 是我们尝试连接的 url 或后端端点。 hero 是我们发送的数据。 this.httpOptions 是我们发送的选项/标头(如果需要)
  • 哦,好吧,我明白了,是的。据我了解,如果在现实生活场景中使用,例如(/api/user/add)的url,应该包含将用户添加到数据库的逻辑,对吗?然后该 api 应该向 addUser 服务返回响应。
  • 是的,后端 url 后面的控制器应该包含数据库连接和操作的逻辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 2017-03-26
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 2017-04-22
  • 2016-12-28
相关资源
最近更新 更多