我用 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
登录后,如果我输入 http://localhost:9000/#/login
或 http://localhost:9000/#/register
,它将进入主页> 或任何其他网址。如果我注销并尝试任何页面,它就会登录。
问题是,登录后,当我尝试 http://localhost:9000/
或关闭选项卡并再次打开网址时,它将进入登录页面(意味着登录的用户是空)。
为什么会发生这种情况?又该如何解决呢?
我需要设置一些cookies之类的吗?如果是这样,怎么办?
最佳答案
好吧,重新加载页面后,您将重新加载应用程序。 $rootScope.loggedUser
变为 null。是的,您可以使用 cookie 来存储 session 。这是 AngularJS docs for cookies
并且不要忘记包含 angular-cookies.js
首先添加模块依赖:
angular.module('mainApp', ['ngCookies'])
第二:注入(inject)$cookieStore服务
angular.module('mainApp', ['ngCookies']).controller('LoginController', function($scope, $location, page, $cookieStore)
第三:使用cookie:
$scope.loginUser=function(){
var isLoggedIn = $cookieStore.get('isLoggedIn');
var name=$scope.user.name;
var pwd=$scope.user.password;
if(name=="1234" && pwd=="1234" || isLoggedIn){
page.setUser($scope.user);
$location.path( "/home" );
$cookieStore.put('isLoggedIn', true);
} else {
$cookieStore.remove('isLoggedIn');
alert("Invalid credentials");
}
}
但请注意,这是一种非常基本、简单且不安全的维持 session 的方法!
关于javascript - AngularJS - 登录并关闭选项卡后,它不会重定向到主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20973253/