totaltool
totaltool

Reputation: 97

how to get access to angular httpClient status attribute in response

I have the following code:

this.http.post(url, payload)
      .subscribe(
        (req:any)=>{
          if(req.status != 200){
            console.log('non 200 status');

this.http is referring to a service I have injected:

post(url, payload){
    return this.http.post(url, payload, { observe: 'response' });
  }

as you can see I am observing the whole response.

when I console log the request I get the httpresponseerror object status and all but for some reason my code is not respecting it.

core.js:14597 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "http://127.0.0.1:8080/api/user/user", ok: false, …}
error: {failcontext: "That email is already in use"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://127.0.0.1:8080/api/user/user: 400 Bad Request"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "Bad Request"
url: "http://127.0.0.1:8080/api/user/user"
__proto__: HttpResponseBase

What am I doing wrong?

Upvotes: 1

Views: 615

Answers (2)

Yoarthur
Yoarthur

Reputation: 917

In you http request add observer

return this.http.post(
    this.configUrl, { observe: 'response' });
}

so you can access the whole object response and not just the data.

Upvotes: 0

totaltool
totaltool

Reputation: 97

I got it by including the error listener:

this.http.post(url, payload)
      .subscribe(
        (req:any)=>{
          console.log(req);

        },
        (err: any)=>{
          if(err.status != 200){
            console.log('non 200 status');
          }
        }
      );

Upvotes: 1

Related Questions