如何在“检查用户的登录状态”功能之前触发 authCheck 工厂?
我正在尝试检查$rootScope
路由和 http 请求的状态:
//Global Logout Function
myApp.run(function($rootScope, $http) {
$rootScope.logout = function() {
$http.post('/api/auth/logout');
};
});
//Check Login state of user
myApp.run(function($rootScope, $http, $window) {
$rootScope.$on('$routeChangeStart', function () {
$http.get('/api/auth')
.then(function successCallback(response) {
$rootScope.logStatus = response.data.data.loggedIn;
console.log('initial ' + $rootScope.logStatus);
}, function errorCallback(response) {
$rootScope.logStatus = response.data.data.loggedIn;
});
return $rootScope.logStatus;
});
});
//Check for authenticated users on http requests (API calls and Routing changes) and redirect to login if logged out
myBirkman.factory('authCheck', ['$rootScope','$window', function($rootScope, $window) {
var authCheck = {
'request': function(config) {
if ($rootScope.logStatus == true) {
//do nothing
console.log('redirect ' + $rootScope.logStatus);
} else if ($rootScope.logStatus == false) {
$window.location.href = '/login.php';
}
},
'response': function(response) {
return response;
}
};
return authCheck;
}]);
// Define routing within the app
myApp.config(['$httpProvider', '$routeProvider', function($httpProvider, $routeProvider) {
$httpProvider.interceptors.push('authCheck');
我试图将 $rootScope 元素转换为常量,但同样的问题出现了。工厂在 run 函数之前运行,因此直到工厂运行之后才会更新常量。