AngularJS $资源拦截器

时间:2014-04-22 15:51:47

标签: angularjs http rest resources interceptor

如何在$resource来电中添加拦截器?

假设我有一个名为Users的资源工厂,就像这样;

app.factory('Users', ['$resource', 'resourceInterceptor',
  function ($resource, resourceInterceptor) {
    return $resource(
      'users/:user_id',
      {
        user_id: '@id'
      },
      {
        query: {
          method: 'GET', // Not changing the default method, just adding an interceptor
          interceptor: resourceInterceptor // Is there any better way to do this.. like globally?
        },
        save: {
          method: 'POST', // Same here
          interceptor: resourceInterceptor // Again...
        },
        ..., // And so on
      }
    );
  }]);

和我的resourceInterceptor服务看起来像;

app.factory('resourceInterceptor', ['$rootScope',
  function ($rootScope) {
    return {
      request: function () {
        // This function isn't executed at all?
        $rootScope.loading = true;
      },
      response: function () {
        $rootScope.loading = false;
      },
      responseError: function () {
        $rootScope.loading = false;
      }
    };
  }]);

首先,永远不会执行request拦截功能,为什么不呢?

其次,必须将拦截器硬编码到现有的$resource方法是非常繁琐的,有没有办法更容易地将拦截器分配给特定的$resource调用,或者甚至可以为所有{{1}分配拦截器调用?

3 个答案:

答案 0 :(得分:15)

要在资源中使用拦截器,您应该:

1 - 使用request,response,responseError:

创建一个httpInterceptor
app.factory('myInterceptor', function () {
    //Code
    //return { request:...,
});

2 - 在您的应用中配置此拦截器:

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('myInterceptor');
}]);

现在你已经将你的httpProvider配置为有一个拦截器,无论你注入$ http,你都会使用这个提供程序,所以...你将执行你的请求,响应和responseError函数。

3 - 在资源中使用它。 由于$ resource使用$ http而你已经配置了一个httpProvider globaly,你将在使用你的资源时调用你的拦截器的函数。

第二个问题: 您不能将拦截器设置为具体的$ http对象,它们(拦截器)是全局设置的。

(即使您在模块定​​义之前设置了拦截器,然后将其删除,也无法知道执行顺序)

如果你不想在每个$ resource动作中覆盖拦截器属性,你可以做什么(当你在你的问题中写下时)你可以改进你的拦截器。

app.factory('userLoadingInterceptor', function () {
    //Code
    return {
        request: function(){
            //Check if your are working with a url related with users
            // and if so do things...
        }
});

答案 1 :(得分:0)

来自文档:

  

拦截器对象有两个可选方法 - response和responseError

我不知道你想要实现什么,但是通用HTTP拦截器可能是另一种选择。

答案 2 :(得分:0)

通用HTTP拦截器应该做你想要的。您可以在此处找到示例:Handle HTTP 302 response from proxy in angularjs

相关问题