使用cookie angularjs登录路线



我正在使用gangularjs登录到我的站点。我的代码:html:

<input type="text" ng-model="username" placeholder="Username">
        <input type="password" ng-model="password" placeholder="Password" >
        <button type="submit" ng-click="login()">Sign in</button>

我的JS:

app.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'login.html'
        })
        .when('/dashboard', {
            resolve: {
                "check": function($location, $rootScope) {
                    if(!$rootScope.valueCookie) {
                        $location.path('/');
                    }
                }
            },
            templateUrl: 'dashboard.html'
        })
        .otherwise({
            redirectTo: '/'
        });
});
     $scope.login = function() {
            $cookieStore.put('cookie', someSessionObj);
        $rootScope.valueCookie = $cookieStore.get('cookie');
        $location.path('/dashboard');
        }

我尝试做的是cookie解决。当cookie在浏览器中 - 单击符号后,我们在" dashboard.html"中,刷新页面后仍然有" dashboard.html"。我的代码不起作用,如果我在" dashboard.html"上刷新页面,它会使我登录。感谢提前回答!

问题是

if(!$rootScope.valueCookie) {
     $location.path('/');
}

每当您刷新页面时,您的$rootScope都不会具有valueCookie。要使它起作用,请在您的运行功能中写下以下代码。

app.config(function() {
   // your code
}).run(function($rootScope, $cookieStore){
   $rootScope.valueCookie = $cookieStore.get('cookie');
});

在仪表板页面上您可以编写ng-init功能

dashboard.html

<div ng-init="myFunction()">

</div>

,在仪表板控制器中,您可以执行此操作

$scope.myFunction = function(){
$scope.valueCookie = $cookieStore.get('cookie');
}

因此,每当您刷新仪表板页面启动功能时,cookie值将存储在$scope变量

最新更新