Angular2、POST响应图错误?
Angular 2, POST response map error?
当我从服务器得到良好响应时,我的以下代码可以正常工作
let response = this.http.post(url,sendData).map(res =>res.json());
return response;
但是,一旦我从服务器收到非 JSON 响应,整个应用程序就开始崩溃。
假设 .json() 给出了这个错误 i try/catch.
let response:any = this.http.post(url,sendData);
return response.map((resp)=>{
try{
resp.json();
}
catch(Error){
return *what to do*;
}
return resp.json();
});
完整代码参考
sendToAPI(sendData,param,option?){
sendData = JSON.stringify(sendData);
let url = this.link+param;
let response:any = this.http.post(url,sendData);
return response.map((resp)=>{
try{
resp.json();
}
catch(Error){
** here ** // need to return a response object
}
return resp.json();
});
}
What could be the possible way out? When due to some reason API gives a non-JSON parsable error. I should give me an object of this following sort to subscribe to:
{
status: 0,
data: [],
message : "non json response by server"
}
因此,在您当前的设置中,一种方法是这样的:
let response:any = this.http.post(url,sendData);
return response.map((resp)=>{
let body = {};
try{
body = resp.json();
}
catch(Error){
body = {
status: 0,
data: [],
message : "non json response by server"
};
}
return body;
});
当我从服务器得到良好响应时,我的以下代码可以正常工作
let response = this.http.post(url,sendData).map(res =>res.json());
return response;
但是,一旦我从服务器收到非 JSON 响应,整个应用程序就开始崩溃。
假设 .json() 给出了这个错误 i try/catch.
let response:any = this.http.post(url,sendData);
return response.map((resp)=>{
try{
resp.json();
}
catch(Error){
return *what to do*;
}
return resp.json();
});
完整代码参考
sendToAPI(sendData,param,option?){
sendData = JSON.stringify(sendData);
let url = this.link+param;
let response:any = this.http.post(url,sendData);
return response.map((resp)=>{
try{
resp.json();
}
catch(Error){
** here ** // need to return a response object
}
return resp.json();
});
}
What could be the possible way out? When due to some reason API gives a non-JSON parsable error. I should give me an object of this following sort to subscribe to:
{
status: 0,
data: [],
message : "non json response by server"
}
因此,在您当前的设置中,一种方法是这样的:
let response:any = this.http.post(url,sendData);
return response.map((resp)=>{
let body = {};
try{
body = resp.json();
}
catch(Error){
body = {
status: 0,
data: [],
message : "non json response by server"
};
}
return body;
});