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
addHero()
method in hero.component.tsaddHero()
method in hero.service.ts- 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'))
);
}