Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the response header of a HttpClient.Post request in Angular

I am using angular 7 and i need to get "Response Header" from the given API in service file without using "subscribe". please help me in this

i have tried by using many google answers but none of them worked.I am not able use subscribe in service.ts file because i am getting error in component.ts file as we can t use subscribe two times

login(email: string, password: string ) {
this.email = email;
this.password = password;


return this.http.post<any>(`this.url/auth/login`, { email, password})
.pipe(map(user => {
var currentuser:any = { user: user.user, token: user.token};
if (currentuser && user.token) {
localStorage.setItem('currentUser', JSON.stringify(currentuser));
this.currentUserSubject.next(currentuser);
 }
return user;
 }));

}

Expected result :

need to get ""response header for the above api .. Note : "Response header" means -- content length , token ,Content-Type , Etag, etcc

Actual result :

I am getting only the body for this not headers

like image 489
Sudhin Avatar asked Jan 01 '23 19:01

Sudhin


1 Answers

My understanding is you would like :

  • to send post request and retrieve data
  • but also have access to headers of server response.

If that's true, you should consider to invoke HttpClient.post() with httpOptions = { observe: 'response' }. With this, HttpClient.post() will return an Observable of typed HttpResponse rather than just the JSON data.

Recommended read on Angular Official docs

Your code should looks like :

this.http.post<HttpResponse<User>>(`${this.url}/auth/login`, { email, password }, 
  { observe: 'response' }).subscribe(response => {

  ...
  response.headers.keys(); // all header names
  ...
  response.body // response content
  ...

});

UPDATED

or inside a service method, which will retrieve a User model only, but will do something with response details, for instance: (may have typos)

getUserFromLogin(email: string, password: string): Observable<User> {
  return this.http.post<HttpResponse<User>>(`${this.url}/auth/login`, 
    { email, password }, { observe: 'response' }).pipe(
      map(response => {

        ...
        response.headers.keys(); // all header names
        ...
        response.body // response content
        ...

        return response.body;
      })
  )
)
like image 187
Thierry Falvo Avatar answered Feb 19 '23 10:02

Thierry Falvo