Elixor
  • Elixor
  • Setup
  • Making a GET request
    • Why write a separate service file
    • Type-checking the response
    • Reading the full response
  • Sending data to the server
    • Adding headers
    • Making a POST request
    • Making a DELETE request
    • Making a PUT request
  • Error handling
    • Getting error details
    • retry()
  • Observables and operators
  • Requesting non-JSON data
  • Advanced Usage
    • Configuring the request
    • Debouncing requests
    • Intercepting requests and responses
    • Listening to progress events
  • Security: XSRF Protection
Powered by GitBook
On this page

Was this helpful?

  1. Sending data to the server

Making a POST request

PreviousAdding headersNextMaking a DELETE request

Last updated 6 years ago

Was this helpful?

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, .

Of course it catches errors in much the same manner .

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.

specify required headers
described above