作为每AngularJS文档:
的$ HTTP服务是核心角服务便于与远程HTTP服务器
从$ HTTP调用的响应对象具有这些 通信属性(除其他外):
数据 - {string | Object} - 使用转换函数转换的响应正文。
status - {number} - 响应的HTTP状态码。您可以使用它来根据不同代码制定逻辑
statusText - {string} - 响应的HTTP状态文本。
在你的例子中,你已经实现了Promise.protorype.then()函数,它允许你委托成功(第一个参数)和错误(第二个参数)进行进一步处理,一旦承诺完成($ http。拨打电话已完成)。
这是我将如何根据您的例子做:
function getProducts() {
// Call the http get function
return $http.get(url).then(
//The request succeeded - 200 status code
function(response) {
products= response.data.result;
return products;
},
//The request failed
function(response) {
// Here you can access the status property and the statusText
console.log("Http Status: " + response.status + " Description: " + response.statusText);
// Return a false result
return false;
});
我通常会使用一个库像Angular-UI-Notification,并清理了一下我实现它是这样的:
//The success handler function
function handle_response_success(response) {
// Do processing here based on the response then show a success notification
Notification.success('Success notification');
};
// The error handler function
function handle_response_error(error) {
Notification.error('Something went wrong with that request. More Info: ' + 'Http Status: ' + error.status + ' Description: ' + error.statusText);
}
// Then finally bind it to your getProducts call
function getProducts() {
// More elegant proto imho
return $http({ method: 'GET',
url: 'http://example.com'
});
};
// More elegant way to handle this imho
getProducts.then(handle_response_success.bind(this), handle_response_error.bind(this);
http://stackoverflow.com/questions/27507678/in-angular-http-service-how-can-i-catch-the-status-of-error – epascarello
你不应该担心状态码200,如果状态代码不是200个代码中的一个,承诺将被'$ http'拒绝 – charlietfl