AngularJS Interceptor TypeError:无法读取未定义的属性"标题"

Cha*_*anX 7 javascript interceptor angularjs

我在尝试实现AJAX Spinner加载代码时出于不明原因获取此错误.

我不明白应该在哪里定义标题.我做了,console.log(config)但我可以看到headers: accept: text/html那里的价值.

以下是我的代码:

/**
* Spinner Service
*/

//Spinner Constants
diary.constant('START_REQUEST','START_REQUEST');
diary.constant('END_REQUEST','END_REQUEST');

//Register the interceptor service
diary.factory('ajaxInterceptor', ['$injector','START_REQUEST', 'END_REQUEST', function ($injector, START_REQUEST, END_REQUEST) {
    var $http,
    $rootScope,
    myAjaxInterceptor = {
        request: function (config) {
            $http = $http || $injector.get('$http');
            if ($http.pendingRequests.length < 1) {
                console.log(config);
                $rootScope = $rootScope || $injector.get('$rootScope');
                $rootScope.$broadcast(START_REQUEST);
            }
        }
    };

    return myAjaxInterceptor;
}]);

diary.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('ajaxInterceptor');
}]);
Run Code Online (Sandbox Code Playgroud)

Qui*_*dam 12

我想我有解决方案.

我在AngularJS项目中遇到了同样的问题,其中拦截器与你的拦截器完全相同(https://docs.angularjs.org/api/ng/service/$http#interceptors)

要缩短,拦截器会捕获配置并且必须返回它.而你忘记了.

那就是:

request: function (config) {
    $http = $http || $injector.get('$http');
    if ($http.pendingRequests.length < 1) {
        $rootScope = $rootScope || $injector.get('$rootScope');
        $rootScope.$broadcast(START_REQUEST);
    }
    return config;
}
Run Code Online (Sandbox Code Playgroud)


Bra*_*lio 1

这里有一个关于如何使用拦截器实现旋转器的完整示例(将 $rootScope 包装在服务中以获得更好的代码可读性)。

http://lemoncode.net/2013/07/31/angularjs-found-great-solution-to-display-ajax-spinner-loading-widget/

正如您所指出的,这是我正在使用的当前结构(简化的内部代码),已被弃用(我必须更新帖子)。我认为最好的办法是从一个 plunkr 开始,也许它与你正在实现的方式无关(让我搜索一个种子 plunkr)

myapp.factory('httpInterceptor', ['$q', '$injector',
    function ($q, $injector) {

    return {
      'request': function(config) {
         // request your $rootscope messaging should be here?
        return config;
      },

     'requestError': function(rejection) {
        // request error your $rootscope messagin should be here?
        return $q.reject(rejection);
      },


      'response': function(response) {
        // response your $rootscope messagin should be here?

        return response;
      },

     'responseError': function(rejection) {
        // response error your $rootscope messagin should be here?

        return $q.reject(rejection);

      }
    };
  }
]);
Run Code Online (Sandbox Code Playgroud)