使用Ionic2从API,http.post获取结果

时间:2016-04-21 14:28:41

标签: angularjs api ionic-framework ionic2

我已使用此代码在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请求中获取错误消息并显示它?

1 个答案:

答案 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);