我的 angularjs spa 中有以下工厂定义:
(function () {
'use strict';
angular.module('snApp')
.factory('Auth', ['$http', 'localStorageService', function ($http, localStorageService) {
//code goes here
}]);
})();
然后在我的应用程序配置中,我有以下 http 拦截器设置:
var app = angular.module('snApp', ['ui.router', 'LocalStorageModule', ])
.config(['$logProvider', '$stateProvider', '$urlRouterProvider', '$httpProvider', '$provide', function ($logProvider, $stateProvider, $urlRouterProvider, $httpProvider, $provide) {
// Intercept http calls.
$provide.factory('RequestHttpInterceptor', function ($q, Auth) {
return {
// On request success
request: function ($config) {
if (Auth.user) {
$config.headers['XToken'] = Auth.user.token;
}
return $config;
}
};
});
// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('RequestHttpInterceptor');
}]);
当我运行该应用程序时,出现以下错误:
Uncaught Error :[$injector:cdep]
我认为它与我的 Auth 中的 $http 有关,因为如果我删除它,它就会起作用,但我需要它!
如果有人能帮助我理解我做错了什么,那就太好了!
最佳答案
好的,我想通了。由于它是一个 http 拦截器,angular 不喜欢你将 $http 传递给你的工厂这一事实 - 这是有道理的,因为如果你在 http 拦截器中调用 $http 它将调用拦截器,它将调用 $http , 等等 等等 得到这个无限循环。
幸运的是,我只需要工厂中的一个属性,所以我将其从 Auth 工厂中抽象出来,这样就不需要 $http 了。还有其他方法可以做到这一点,但这对我来说是最好的解决方案。
关于javascript - angularjs中的循环引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20759433/