2016-04-21 69 views
-1

我已經使用這個代碼,以使在http.post充分利用API,http.post結果與Ionic2

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

中的第二個參數是訂閱的錯誤,第三是「終於」

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); 
+0

不,我不想要的錯誤。其實我想從API –

+0

這個消息返回比它的第一個參數,但你有它空..它應該是 '''this.http.post('https://api.example.com/v1/auth/寄存器」,creds,{ 頭:頭 }) .MAP(RES => res.json()) .subscribe( (messageFromApi)=>的console.log(messageFromApi) )''' –

+0

是否返回消息仍然可以用http.post讀取,甚至API的頭文件代碼爲400? –