2

每次我使用任何 $resource 访问服务器时,我都想在失败时向我的用户显示相同的警报。

今天,它看起来像:

function tryAgain() { alert("try again") }
myResource.query().$promise.catch(tryAgain);
myResource.update(...).$promise.catch(tryAgain);
myResource.delete(...).$promise.catch(tryAgain);
otherResource.query().$promise.catch(tryAgain);

有没有办法为 ngResource 配置默认的错误处理功能?我正在寻找类似的东西:

$resource.somethingMagicHere.defaults.catch(tryAgain);
4

3 回答 3

6

您可以在您的部分中使用拦截器app.config()。这将捕获源自$httpwhich $resourceuses 的所有响应错误。

$httpProvider.interceptors.push(function($q) {
  return {
    'responseError': function(response) {
      if (response.status == 401) {
        // Handle 401 error code
      }
      if (response.status == 500) {
        // Handle 500 error code
      }

      // Always reject (or resolve) the deferred you're given
      return $q.reject(response);
    }
  };
});
于 2014-05-02T01:27:59.967 回答
1

@kba 的答案帮助我找到了路径。下面这篇文章让我明白了:

http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

于 2014-05-02T02:26:39.493 回答
0

只需声明一次并重用:

var defaultErrorHandler = function() {
  alert("try again")
}

myResource.query(...).$promise.catch(defaultErrorHandler());            
myResource.update(...).$promise.catch(defaultErrorHandler());
...
于 2014-05-02T01:12:54.297 回答