在我的 angularjs 的 app.run 域中,我正在尝试检查是否定义了 cookie,如果未定义,则将用户重定向到登录页面。如果定义了 cookie,则页面加载良好到页面,但如果 cookie 未定义,则页面加载效果不佳,因为它在登录页面上以无限循环不断刷新或重新加载。
这是片段
app.run(["$rootScope","$location", "$cookies", function($rootScope, $location, $cookies) {
var token = $cookies.getObject('token');
if (token !== undefined) {
$rootScope.user = token;
$location.path(originalPath);
}else{
alert("5900");
$(location).attr('href', '/login');//when cookie token is not defined, this window keeps loading endlessly
}
while 是登录 URL,当令牌未定义时无休止地重新加载
如果您已经在登录页面上,则可以添加提前转义:
app.run(["$rootScope","$location", "$cookies", function($rootScope, $location, $cookies) {
if (window.location.href.match(//login/)) {
return;
}
var token = $cookies.getObject('token');
if (token !== undefined) {
$rootScope.user = token;
// Commented this line out, because if there's a token, the user doesn't need to be redirected anywhere
// $location.path(originalPath);
} else {
alert("5900");
$(location).attr('href', '/login');//when cookie token is not defined, this window keeps loading endlessly
}
附言为什么不使用$location.path('login')
重定向到登录页面?$location.path
既是二传手又是获取者,如文档中所述。
编辑:注释掉带有解释的行$location.path(originalPath);
尝试检查登录页面上是否已经存在,如下所示,
var currentUrl = window.location.href;
if(currentUrl.indexOf('login') != -1){
//Already login
}
else{
//Not login
}