Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HttpClient post request type

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.

like image 406
user8972341 Avatar asked Dec 18 '25 22:12

user8972341


1 Answers

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.

like image 171
Ashish Ranjan Avatar answered Dec 21 '25 12:12

Ashish Ranjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!