简体   繁体   中英

How do I get the response code in angular 7

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'
        })
      }

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM