我已使用此代码在http.post
上进行调用var creds = encodeURI("name="+name+"&email="+email);
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Accept', 'application/json');
this.http.post('https://api.example.com/v1/auth/register', creds, {
headers: headers
})
.map(res => res.json())
.subscribe(
() => console.log('Registration Complete')
);
从上面的代码中,API可能会返回如下所示的错误消息。
{
"error": "Validation error.",
"errors": [
"The username has already been taken.",
"The email must be a valid email address."
]
}
如何从API请求中获取错误消息并显示它?
答案 0 :(得分:1)
订阅中的第二个参数是错误,第三个参数是'finally'
this.http.post('https://api.example.com/v1/auth/register', creds, {
headers: headers
})
.map(res => res.json())
.subscribe(
() => console.log('Registration Complete')
), (err) => console.log(err);