【问题标题】:Circular dependency with $compile $http循环依赖与 $compile $http
【发布时间】:2014-05-07 01:50:26
【问题描述】:

使用咆哮角指令时出现循环依赖错误:

错误:[$injector:cdep] 找到循环依赖:spinnerInterceptor 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');
}]);

我该如何解决这个问题?

【问题讨论】:

    标签: angularjs inject growl


    【解决方案1】:

    不要在你的拦截器中注入$compile,而是注入$injector并用$injector.get('$compile')获取$compile(不在拦截器初始化时间)。例如,您可以在 responseError 方法中填写一次闭包变量 $compile

    【讨论】:

    • 这似乎解决了循环依赖问题!但是,我现在遇到了一个问题,实际上是在清理我试图 $compile 的 HTML。我得到 html.indexOf 不是一个函数。
    • 您的最后一个问题可能与返回 $compile 的内容有关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2010-09-12
    • 2021-10-02
    • 1970-01-01
    相关资源
    最近更新 更多