所以我有一个服务定义如下:
angular.module('services', ['ngResource'])
.factory('Things', function ($rootScope, $http) {
var basePath = 'rest/things/';
return {
getAll: function() {
return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {});
}
};
});
然后,在其他地方,我认为消费服务W /:
Things.getAll().success(function(things){
//do something w/ things
})
.error(function(err){
// Clearly, something went wrong w/ the request
});
我想什么做的,是能够例如,如果服务级别的数据存在问题,则“抛出”错误条件。即:
数据回来为:
{
status:500,
message:'There was a problem w/ the data for this client'
}
因此然后在那里的服务会是这样的:
getAll: function() {
return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {})
.throwError(function(data){
return (data.status && data.status == 200);
});
}
所以当throwError回调返回false,误差()的承诺然后会被称为而不是成功的承诺。
有没有人有关于如何做到这一点的任何想法?
非常感谢!
创建您服务延迟。实际上,钩入'$ http'调用的**成功**和**错误**回调。在** success **里面,检查响应的'status'属性;如果它不在'200'范围内,**拒绝**延期。否则,**解决**延期。 **拒绝** **错误**回调中的任何内容。并从服务方法 – Ian
返回延期的**许诺**伊恩,谢谢..你能给出一个代码示例作为答案吗? 另外,我应该为此使用拦截器吗? http://docs.angularjs.org/api/ng.$http – RavenHursT
如果你确定所有的请求都遵循这个约定,那么使用拦截器肯定更有意义。你可以像在这个页面的例子中那样创建拦截器,并且在'response'回调中,检查响应的属性'status'和它是否'bad',使用'$ q.reject(response);'否则返回响应|| $ q.when(response);' – Ian