Angular Tour of Heroes

641 Views Asked by At

I am currently learning angular using the angular tour of heroes. I am slightly getting the concepts by following the examples. I am now in adding a new hero. For those who finished the tutorial, I just have question.

In the add hero, I can't get my head around it. Would you help me understand how the addHero() method added the new hero on the server? I am expecting a method that will do this. But I didn't see any add method.

I came from PHP/JS, jQuery background. So I was expecting something like this

  1. addHero() method in hero.component.ts
  2. addHero() method in hero.service.ts
  3. Coming from PHP MVC, addHero() method in model that will update the data in the database.

Hope you bear with me, I want to understand how it works before proceeding to the next step.

Thank you everyone.

src/app/heroes/heroes.component.ts (add)

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

1

There are 1 best solutions below

4
vsnikhilvs On
  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.