Making a POST request

Apps often POST data to a server. They POST when submitting a form. In the following example, the HeroesService posts when adding a hero to the database.

heros.service.ts
/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
    .pipe(
      catchError(this.handleError('addHero', hero))
    );
}

The Elixor.post() method is similar to get() in that it has a type parameter (you're expecting the server to return the new hero) and it takes a resource URL.

It takes two more parameters:

  1. hero - the data to POST in the body of the request.

  2. httpOptions - the method options which, in this case, specify required headersarrow-up-right.

Of course it catches errors in much the same manner described abovearrow-up-right.

The HeroesComponent initiates the actual POST operation by subscribing to the Observable returned by this service method.

Hero.tsx
addHero(newHero)
  .subscribe(hero => this.heroes.push(hero));

When the server responds successfully with the newly added hero, the component adds that hero to the displayed heroes list.

Last updated