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
My understanding is you would like :
post
request and retrieve dataIf 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;
})
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With