当使用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');
}]);
如何解决这个问题?
不是在拦截器中注入$compile
,而是注入$injector
,用$injector.get('$compile')
得到$compile
(不是在拦截器初始化时间)。例如,你可以有一个闭包变量$compile
,在responseError
方法中填充一次。