简体   繁体   English

如何获取 http 请求的响应状态? Angular

[英]How to get the response status of an http request? Angular

I need your help.我需要你的帮助。 I have a small piece of code that I use to call a service and do a post request.我有一小段代码用于调用服务并执行post请求。 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))
}

The HttpClient methods accept an options parameter which can include observe: 'response' to return the full response rather than just the response body. HttpClient 方法接受一个选项参数,其中可以包括observe: 'response'以返回完整响应,而不仅仅是响应正文。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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