我有一个角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坏请求,但也会有一个JSON主体:
{
Status: "Error",
Body : "Something happened"
}如何在我的错误处理中访问它?
发布于 2019-01-01 14:06:08
你可以这样做(用角6测试)
首先调用其他类中的api,即(api助手服务)
MyApiCall(data:any) {
return this.http.post('Your api url', data);
}在上面的方法中,不要将.map或.subscribe添加到http方法
现在,从要与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;^^这将获得httpresponse给您(状态、代码、httpurl、其他api信息)
let response = data.json();^^这将获得api创建和发送的数据(实际业务响应)。
有错误的逻辑也是如此。
let httpresponse = err;
let response = err.json();^1行获取基本http响应^2行,给出在api (用户自定义主体)中创建的错误消息。
https://stackoverflow.com/questions/51557720
复制相似问题