4

I have the following code in an angular 7 app

insertAccount(submittedAccount:Account):Observable<Account>{
    return this.http.post<Account>(this.baseApiUrl+"Account",submittedAccount,this.httpNormalOptions).pipe(
      map(response=>{
        return response;
      }
    ))
   }

How do I get the http response code? For instance if it returns a 401 error I need to handle it and currently it is obviously simply returning the object.

----Update----

Okay so I followed the solutions below but the map method was never reached as there was no response as such (I assume because it failed due to a 401)

So I changed it to the following

let result:Account[]=[];
    this.http.get<HttpResponse<Account[]>>(this.baseApiUrl+"Account",this.httpNormalOptions).pipe(map(
      response=>{
       return response;
      }
    )).subscribe(r=>{result= r.body},p=>{if(p.status===401){this.clearToken()}})

    return result;

However is obviously now does not return an observable... Is that an issue? (I am pretty new to observables) Is there a benefit to returning an observable over simply returning the Account[] object?

Just for completeness I am building the headers I send with the response as follows

this.httpNormalOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + this.auth_token,
          observe:'response'
        })
      }
coolblue2000
  • 3,796
  • 10
  • 41
  • 62
  • 1
    Possible duplicate of [How can get HttpClient Status Code in Angular 4](https://stackoverflow.com/questions/46639154/how-can-get-httpclient-status-code-in-angular-4) – Igor May 08 '19 at 17:43
  • Possible duplicate of [Catching errors in Angular HttpClient](https://stackoverflow.com/q/46019771/1260204) – Igor May 08 '19 at 17:43
  • It is not a direct duplicate as I have a further issue that is not answered by the listed questions – coolblue2000 May 08 '19 at 23:18
  • Possible duplicate of [How to catch exception correctly from http.request()?](https://stackoverflow.com/q/35326689/1260204) – Igor May 09 '19 at 09:39

1 Answers1

4

You need to tell Angular you want to get the complete response with the option observe: 'response', this will give you access to the headers and the status code:

this.http.post<Account>(url, { observe: 'response' }).pipe(
    map(response => response.headers['status'])
)

The response will be of type HttpResponse<Account>.

jo_va
  • 13,504
  • 3
  • 23
  • 47