$ compile $ http的循环依赖

时间:2014-03-27 20:35:12

标签: angularjs inject growl

使用growl angular指令时出现循环依赖性错误:

  

错误:[$ injector:cdep]找到循环依赖项:spinnerInterceptor< - $ http< - $ compile http://errors.angularjs.org/1.2.11/$injector/cdep?p0=spinnerInterceptor%20%3C-%20%24http%20%3C-%20%24compile

   angular.module('bedrock').factory('spinnerInterceptor', ['$q', 'growl', '$injector', function($q, growl, $injector) {
  var count = 0;

  function setCount(count) {
    $('#spinner .count').text(count);
  }

  return {
    request: function(config) {
      /* jshint -W017 */
      if (!count++) {
        // Start a spinner here.
        $('#spinner').show();
      }
      /* jshint +W017 */
      setCount(count);

      return config || $q.when(config);
    },
    response: function(response) {
      if (!--count) {
        // Stop the spinner here...
        $('#spinner').hide();
      }
      setCount(count);

      return response || $q.when(response);
    },
    responseError: function(rejection) {
      if (!--count) {
        // ...and here.
        $('#spinner').hide();
      }
      setCount(count);
      var $compile = $compile || $injector.get('$compile');
      if(rejection.status != 401){
        growl.addErrorMessage($compile(
            '<h3>' + rejection.config.method + ' '+ rejection.config.url + '</h3>' +
            '<hr><div>' +
                (_.isObject(rejection.data) ? ('<pre>' + JSON.stringify(rejection.data, null, 2) + '</pre>') : rejection.data) +
                '</div>' + '<a ng-click="reportError($event)"><i class="fa fa-bullhorn hoverable"></i>  Report this error</a>'),
          {
            enableHtml: true
          }
        );
      }

      return $q.reject(rejection);
    }
  };
}]).factory('timeoutInterceptor', function() {
  return {
    request: function(config) {
      config.timeout = 20000;
      return config;
    }
  };
}).config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push('spinnerInterceptor');
  $httpProvider.interceptors.push('timeoutInterceptor');
}]);

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

不是在拦截器中注入$compile,而是注入$injector并使用$compile获取$injector.get('$compile')(不在拦截器启动时间内)。例如,您可以使用$compile方法填充一次的闭包变量responseError