How can get HttpClient Status Code in Angular 4
Asked Answered
W

1

47

In Http Module I can easily get the response code using response.status, but when I used HttpClient Module I cannot get the response.status, it shows undefined.

So, how can I get the response.status using HttpClient module in Angular 4. Please help.

Whitleather answered 9/10, 2017 at 5:5 Comment(4)
This is all explained here: angular.io/guide/httpIta
I checked the documentation but I didn't find the exact solution to find the status code from response.Whitleather
Look at the section "Reading the full response".Ita
Thanks for your help... It works now.Whitleather
C
83

From this section, this is the adjusted code

http
  .post<T>('/yoururl', whateverYourPostRequestIs, {observe: 'response'})
  .subscribe(resp => {
     console.log(resp);
  });

the answer is {observe: 'response'}. you can then view the logged resp and pick/choose what you want.

Counterforce answered 18/10, 2017 at 11:21 Comment(6)
As the method is post, {observe: 'response'} would be sent as a request body. So that should be on the third parameter.Silverplate
It's still not clear hot to get the status! I'm only getting the body.Pelson
But I need the second argument to send custom headers for authentications. How can still add {observe: 'response'}?Pelson
@LeeMoe Thats no problem! Since the thrid parameter of the post request is taking in an object, you can pass in both. For details see my answer below! :)Valerievalerio
@LeeMoe, you’ll want to look into interceptors for things like authentication. There are both request and response interceptors that you can set up to manage things like error codes, authentication etc...Counterforce
can someone please answer my query also. #54827879Doublebank

© 2022 - 2024 — McMap. All rights reserved.