我用 yeoman、grunt 和 bower 创建了一个 angularJS 应用程序。我尝试了一个简单的登录示例。登录后会跳转到首页。对于任何路线更改,它将检查用户是否已登录。如果登录,它将重定向到主页或特定路由,否则重新路由到登录页面。这一切对我来说都很好。
这是app.js
'use strict';
//Define Routing for app
angular.module('mainApp', []).config(['$routeProvider', '$locationProvider',
function($routeProvider,$locationProvider) {
$routeProvider
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'RegisterController'
})
.when('/home', {
templateUrl: 'views/home.html',
controller: 'homeController'
})
.otherwise({
redirectTo: '/home'
});
}])
.run( function($rootScope, $location) {
// register listener to watch route changes
$rootScope.$on( "$routeChangeStart", function() {
var url=$location.path();
var location=url.replace("/","");
var authnotallowed=false;
if(location.indexOf("login")!=-1||location.indexOf("register")!=-1){
authnotallowed=true
}
if ( $rootScope.loggedUser == null ) {
// not logged user, should be going to #login
if(authnotallowed){
$location.path(url);
} else{
$location.path( "/login" );
}
} else {
// not going to #login, should redirect now
if(authnotallowed){
$location.path("/home");
} else{
$location.path(url);
}
}
});
});
angular.module('mainApp').factory("page", function($rootScope){
var page={};
var user={};
page.setUser=function(user){
$rootScope.loggedUser=user;
}
return page;
});
这是我的loginControler.js
'use strict';
angular.module('mainApp').controller('LoginController', function($scope, $location, page) {
$scope.user = {};
$scope.loginUser=function(){
var name=$scope.user.name;
var pwd=$scope.user.password;
if(name=="1234" && pwd=="1234"){
page.setUser($scope.user);
$location.path( "/home" );
} else {
alert("Invalid credentials");
}
}
});
一切对我来说都很好。
由于我使用的是 grunt,所以 url 就像http://localhost:9000/#/login
登录后它会转到主页,如果我输入 like http://localhost:9000/#/login
orhttp://localhost:9000/#/register
或任何其他 url。如果我注销并尝试任何页面,它就会登录。
问题是,当我尝试登录http://localhost:9000/
或关闭选项卡并再次打开 url 后,它将进入登录页面(意味着loggedUser 为空)。
为什么会这样?我该如何解决?
我需要设置一些cookies或其他东西吗?如果是这样,怎么做?