如何在响应中访问有角度的httpClient状态属性

时间:2018-12-29 23:51:49

标签: angular typescript angular-httpclient

我有以下代码:

this.http.post(url, payload)
      .subscribe(
        (req:any)=>{
          if(req.status != 200){
            console.log('non 200 status');

this.http指的是我注入的服务:

post(url, payload){
    return this.http.post(url, payload, { observe: 'response' });
  }

如您所见,我正在观察整个响应。

当我控制台记录请求时,我得到了httpresponseerror对象状态,但由于某种原因,我的代码不尊重它。

core.js:14597 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "http://127.0.0.1:8080/api/user/user", ok: false, …}
error: {failcontext: "That email is already in use"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://127.0.0.1:8080/api/user/user: 400 Bad Request"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "Bad Request"
url: "http://127.0.0.1:8080/api/user/user"
__proto__: HttpResponseBase

我在做什么错了?

2 个答案:

答案 0 :(得分:0)

我通过包含错误侦听器得到了它:

this.http.post(url, payload)
      .subscribe(
        (req:any)=>{
          console.log(req);

        },
        (err: any)=>{
          if(err.status != 200){
            console.log('non 200 status');
          }
        }
      );

答案 1 :(得分:0)

在您的http请求中添加observer

return this.http.post(
    this.configUrl, { observe: 'response' });
}

因此您可以访问整个对象响应,而不仅仅是数据。