Home > OS >  How to get the response status of an http request? Angular
How to get the response status of an http request? Angular

Time:08-11

I need your help. 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? Thank you very much

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

CodePudding user response:

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

CodePudding user response:

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;
   }));
}
  • Related