我正在尝试在 XHR 请求中发送额外的标头(使用 $resource 初始化)。以下是我的配置
var app = angular.module('app',['angularMoment']).
run(function ($rootScope,$location,$route, $timeout, $http) {
var token = localStorage.getItem("userToken");
$http.defaults.headers.common.token = token;
}
我正在更改哈希参数(例如在登录过程之后)以在应用程序中导航。因此,当我在登录过程后(没有手动重新加载)发送任何 XHR 请求时,它会将令牌(请求标头)作为NULL发送。但是当我手动重新加载我的页面时它工作正常(即发送令牌作为标题)。我也尝试过,$route.reload()
但它不起作用。
请建议我怎样才能摆脱这个问题。
谢谢
编辑 :
尝试使用以下代码后:
app.factory('tokenInterceptorService', ['$q', '$location', function ($q, $location) {
var tokenInterceptor = {};
var request = function (config) {
config.headers = config.headers || {};
var token = localStorage.getItem("userToken");
config.headers.token = token;
return config;
}
// if response errors with 401 redirect to lgoin
var response = function (rejection) {
if (rejection.status === 401) {
$location.path('/');
}
return $q.reject(rejection);
}
tokenInterceptor.request = request;
tokenInterceptor.response = response;
return tokenInterceptor;
}]);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('tokenInterceptorService');
});
app.run(function ($rootScope, $location,$route, $timeout, $http) {
$rootScope.config = {};
$rootScope.config.app_url = $location.url();
$rootScope.config.app_path = $location.path();
$rootScope.layout = {};
$rootScope.layout.loading = false;
$rootScope.$on('$routeChangeStart', function () {
//need to validate
console.log($rootScope.isValidated + "app");
//show loading
$timeout(function(){
$rootScope.layout.loading = true;
});
});
$rootScope.$on('$routeChangeSuccess', function () {
//hide loading
$timeout(function(){
$rootScope.layout.loading = false;
}, 200);
});
$rootScope.$on('$routeChangeError', function () {
alert('Something went wrong. Please refresh.');
$rootScope.layout.loading = false;
});
})
它停止使用“ .run ”渲染应用程序中的视图并陷入$rootScope.$on('$routeChangeError',
并给出错误Error: [$rootScope:inprog] $digest already in progress。