2014-02-07 56 views
2

所以我有一个服务定义如下:

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,误差()的承诺然后会被称为而不是成功的承诺。

有没有人有关于如何做到这一点的任何想法?

非常感谢!

+1

创建您服务延迟。实际上,钩入'$ http'调用的**成功**和**错误**回调。在** success **里面,检查响应的'status'属性;如果它不在'200'范围内,**拒绝**延期。否则,**解决**延期。 **拒绝** **错误**回调中的任何内容。并从服务方法 – Ian

+0

返回延期的**许诺**伊恩,谢谢..你能给出一个代码示例作为答案吗? 另外,我应该为此使用拦截器吗? http://docs.angularjs.org/api/ng.$http – RavenHursT

+1

如果你确定所有的请求都遵循这个约定,那么使用拦截器肯定更有意义。你可以像在这个页面的例子中那样创建拦截器,并且在'response'回调中,检查响应的属性'status'和它是否'bad',使用'$ q.reject(response);'否则返回响应|| $ q.when(response);' – Ian

回答

4

如果您确定所有请求都遵循约定,其中响应返回的数据包含状态代码,那么使用HTTP Interceptor是有意义的。要做到这一点,你可以创建一个服务,并将它推到拦截列表中$httpProvider

.factory("myHttpInterceptor", function ($q) { 
    return { 
     response: function (response) { 
      if (response.data.status && (response.data.status === 500)) { 
       return $q.reject(response); 
      } 
      return response || $q.when(response); 
     } 
    }; 
}); 

您可以用类似>= 400更换=== 500来处理所有的错误,不只是一个500

而且里面你的模块.config(),补充一点:

$httpProvider.interceptors.push("myHttpInterceptor"); 

参考文献:

+1

太棒了。谢谢伊恩! – RavenHursT