如果未定义cookie,则尝试导航用户以进行登录

时间:2018-05-29 13:18:55

标签: angularjs cookies

在我的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,当令牌未定义时无休止地重新加载

2 个答案:

答案 0 :(得分:0)

如果您已经在登录页面上,可以添加早期转义:

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
}

P.S。为什么不使用$location.path('login')重定向到登录页面? 如documentation中所述,$location.path既是定位者又是吸气者。

编辑:注释掉$location.path(originalPath);行并附上说明

答案 1 :(得分:0)

尝试检查登录页面是否已经存在,如下所示:

render() {
    return (
      <ScrollView>
      <View>
        <Text>Test screen</Text>
      </View>
      </ScrollView>
     );
  }
}