美好的一天!我试图在每个页面上检查user_id cookie,如果没有cookie,则重定向到登录页面。但是由于递归,出现问题并且应用程序崩溃了。 为什么这段代码不起作用? 在app.js我有
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
$routeProvider.when('/signup', {templateUrl: 'partials/signup.html', controller: 'signupCtrl', resolve: {factory: checkRouting}});
$routeProvider.when('/index', {templateUrl: 'index.html', controller: 'MainCtrl', resolve: {factory: checkRouting}});
$routeProvider.otherwise({redirectTo: '/'});
}]);
var checkRouting = function ($q, $rootScope, $http, $location, localStorageService) {
function redirect(path) {
if ($location.path() != path) {
$location.path(path);
return $q.reject();
} else {
return true;
}
}
return getUserDataPromise($q, $rootScope, $http, localStorageService)
.then(function (result) {
return redirect("/index");
}, function (reason) {
console.error(reason);
return redirect("/");
});
};
var getUserDataPromise = function ($q, $rootScope, $http, localStorageService) {
if ($rootScope.session_id) {
return $q.when($rootScope.session_id);
} else {
var session_id = localStorageService.cookie.get("session_id");
if (!session_id) {
return $q.reject("No session id.");
} else {
$rootScope.session_id = session_id;
return $q.when(session_id);
// return $q.reject("Error requesting server: " + reason);
}
}
controllers.js是
angular.module('myApp.controllers', [])
.controller('MainCtrl', ['$scope', '$http', '$window', '$route', '$location', '$routeParams', function($scope, $http, $window, $route, $location, $routeParams) {
console.log("fffffffff");
}])
.controller('loginCtrl', ['$rootScope', '$scope', '$http', '$window', '$route', '$location', '$routeParams', 'localStorageService', function($rootScope, $scope, $http, $window, $route, $location, $routeParams, localStorageService) {
$scope.username = "";
$scope.password = "";
$scope.auth = false;
$rootScope.session_id="";
var sess="mlvdfmvlkcmlkvnxclkjmnvkl561vfd" //for debug
$scope.submit = function() {
$scope.secret = "M"
var responsePromise = $http.post("ajax", { method: "login", login: $scope.username, password: $scope.password, secret: $scope.secret });
responsePromise.success(function(data, status, headers, config) {
if (data.status == "done") {
$scope.auth = true;
console.log(data.status);
localStorageService.cookie.set("session_id", sess);
$location.path( "/index" );
};
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX failed!");
});
};
}])
答案 0 :(得分:0)
使用routeChageStart事件,并在用户没有会话时拦截路由更改。
例如:
$rootScope.$on('$routeChangeStart', function (event, next, current) {
// if route requires auth and user is not logged in
if (userIsLoggedIn()==false) {
// redirect back to login
$location.path('/login');
}
});
这样,如果用户未经过身份验证,任何应用程序网址都会重定向登录。
答案 1 :(得分:0)
非常感谢您的回答。 我明白我遇到麻烦的地方。我不应该重定向到" / index"页。当我创建" partials / main"页面和更新的代码重定向到" / main",递归已经消失。