Angular 6 HttpClient错误详细信息

3

我有一个Angular 6应用程序,当我发出http请求时:

this.myService.login(this.form.email.value, this.form.password.value)
    .pipe(first())
    .subscribe(
         data => 
                {
                       //do something on success
                },
         error => 
                {
                     //here the response `error` if I use console.log(error)
                     //shows just Bad request if my API returns 404. 
                     //How can I access other properties of the error, like 
                     //the body?
                }
);

如果HTTP调用返回错误,我如何访问错误的其他属性?

在出现错误的情况下,API将返回404 Bad Request,但也会有一个JSON主体:

{
    Status: "Error",
    Body : "Something happened"
}

如何在错误处理中访问此内容?


在HTTP请求中使用 this.http.get(url, { observe: 'response' });。您将获得响应状态以及所有详细信息。 - Sujata Chanda
1个回答

1

您可以用以下方式实现(已在Angular 6上测试

首先,在其他类中调用API,即(API帮助器服务)

MyApiCall(data:any) {
    return this.http.post('Your api url', data);
  }

在上述方法中,不要将.map.subscribe添加到http post方法中。
现在,从您将与API交互的组件类中调用此方法。
formSubmit() {
     // your logic
      this.apiservice.MyApiCall(apivalues)
        .subscribe(
          data => {
            let httpresponse = data;
            let response = data.json();
            if (httpresponse.status == 200) {
               // logic when success
              }
              else {
               // else
              }
            }
          }, err => {
            let httpresponse = err;
            let response = err.json();
            if (httpresponse.status == 0) {
                //if api is dead or couldn't reach
            }
            else {
              //for other request , 401 404 etc
            }
          });
    }
  }

获取成功代码,

    let httpresponse = data;

^^ 这将向您提供HTTP响应(状态、代码、httpurl、其他API信息)

    let response = data.json();

^^ 这将获取API创建和发送的数据(实际业务响应)

错误逻辑也是相同的

    let httpresponse = err;

    let response = err.json();

^^^ 第一行获取基本的 HTTP 响应 ^^^ 第二行提供了在 API 中创建的错误消息(用户自定义正文)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接