[英]Circular dependency found in angular js
試圖為我的每個請求添加攔截器標頭,但是,這給了我下面的錯誤。
未捕獲的錯誤:[$ injector:cdep]找到循環依賴項:$ http <-Auth <-httpRequestInterceptor <-$ http <-$ templateRequest <-$ route
app.js
var app= angular.module('myDemoApp',['ngRoute'])
app.factory('httpRequestInterceptor', ['Auth', function (Auth) {
return {
request: function (config) {
config.headers['x-access-token'] = Auth.getToken();
return config;
}
};
}]);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});
驗證服務
(function () {
'use strict';
myDemoApp.factory('Auth', ['$http', '$window', Auth]);
/******Auth function start*****/
function Auth($http, $window) {
var authFactory = {};
authFactory.setToken = setToken;
authFactory.getToken = getToken;
return authFactory;
/*setToken function start*/
function setToken(token) {
if (token) {
$window.localStorage.setItem('token', token);
} else {
$window.localStorage.removeItem('token');
}
}
/*getToken function start*/
function getToken() {
return $window.localStorage.getItem('token')
}
}
})();
您不能這樣做,因為。
您已經創建了攔截所有$http
請求的httpRequestInterceptor
。
現在,您正在httpRequestInterceptor
中傳遞Auth
。
如果看到的話, Auth
會在自己內部使用$http
請求。
因此,您的interceptor
器本身可以使用Auth
引發http
請求。
因此,它的循環錯誤和angularjs
不允許您這樣做!
從Auth
工廠中刪除$http
, 或者不要將服務插入本身使用$http
攔截器中。
希望您知道如何創建無限循環鏈,從而導致circular dependency
錯誤!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.