3

The official Angular HttpClient documentation gives the following example for making a POST request to some backend server.

/** 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))
    );
}

But I'm confused as to why the Observable is returning Hero data, or data other than a success code at all for that matter on a POST request. I understand why a GET request would use a type assertion, but don't quite understand how this works.

user8972341
  • 75
  • 1
  • 1
  • 7

3 Answers3

1

Yeah! that is true, a POST will return with a success code. I don't know what is the actual reason its mentioned this way in the docs, but I will write what I understand. (was difficult to write in comments:)

A response from a POST request will depend upon how you have implemented your API. For example your database has some default values set for any POST request, say createDate of Hero and you want the createDate in your angular application. What will you do? you will send the Hero data from the API.

As far as it is implemeted in the docs, they are using mock-api. If you would log the response, you would see a status of 204. By default, with this status, body is not sent. But if you would configure your mock service like:

HttpClientInMemoryWebApiModule.forRoot(InMemHeroService, {put204: false, post204: false})

You will get 200 response with the body, which will be Hero body.

Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
0

In that example, addHero seems to be part of a heroes "service" that gets injected into the HeroesComponent. HeroesComponent then subscribes to that service method and pushes the hero that was returned from the server to the heroes array.

Here is the HeroesComponent subscribing to the addHero observable. HeroesComponent initiates the POST method by subscribing to the observable returned by the service method. :

this.heroesService.addHero(newHero)
  .subscribe(hero => this.heroes.push(hero));
Dream_Cap
  • 2,292
  • 2
  • 18
  • 30
0

The reason is an Web API that accepts POST requests usually returns the created object as a response.

This backend behavior is especially useful when you need to get certain properties (ID, createdTime, etc.) which are only available after the object is created by the POST request at the backend.

See https://stackoverflow.com/a/28951049/1608690 more for info.

Kelvin Lai
  • 2,209
  • 7
  • 24
  • 26