AngularJS ngResource:如何始终使用相同的catch功能?

bar*_*olo 2 angularjs ngresource

每次我使用任何$资源命中服务器时,我都希望在用户失败时向我的用户显示相同的警报.

今天看起来像:

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);
Run Code Online (Sandbox Code Playgroud)

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

$resource.somethingMagicHere.defaults.catch(tryAgain);
Run Code Online (Sandbox Code Playgroud)

kba*_*kba 6

您可以在您的部分中使用拦截器app.config().这将捕获源自$http哪些$resource用途的所有响应错误.

$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);
    }
  };
});
Run Code Online (Sandbox Code Playgroud)