-1

I have a small piece of code that I use to call a service and do a post request. The fact is that I need to get the status of the response from the request. The fact is that I subscribe to a request from the service and I need to type it specifically for my application and I cannot get the status. Tell me what am I doing wrong?

In component

this.service.sendParams(constConnectBody).subscribe((profile: IProfile) => {
   this.profile = profile;
}, (res) => console.log(res.status)); // nothing

In service

public sendParams(body: any):Observable<any> {
   return this.httpClient.post<any>(`this.url`, body)
}

or in the service

responseStatus: any

public sendParams(body: any):Observable<any> {
   return this.httpClient.post<any>(`this.url`, body, {observe: response}).pipe(map(res => this.responseStatus = res.status))
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Dmitry Chernyak
  • 295
  • 3
  • 12

2 Answers2

3

The HttpClient methods accept an options parameter which can include observe: 'response' to return the full response rather than just the response body.

return this.httpClient.post<any>('this.url', body, {observe: 'response'})

See https://angular.io/api/common/http/HttpClient#options for details

Alex
  • 848
  • 6
  • 7
0

based on your comments you can do it like this

responseStatus: any

public sendParams(body: any):Observable<IProfile> {
   return this.httpClient.post<IProfile>(this.url, body, {observe: 'response'}).pipe(map(res => {
      this.responseStatus = res.status;
      return res.body;
   }));
}
Zerotwelve
  • 2,087
  • 1
  • 9
  • 24
  • Ok, thank you) One more question: why i got nothing in the console log, when i call the my variable response status in component? – Dmitry Chernyak Aug 10 '22 at 11:46
  • you your code: `.subscribe((profile: IProfile) => {this.profile = profile;}, (res) => console.log(res.status)); // nothing` (res) is the error case not the satatus code. Please read more about obsevables https://rxjs.dev/ – Zerotwelve Aug 10 '22 at 12:28