首页 > 解决方案 > 一旦用户在 Angular js 中注销,重定向到登录页面而不是仪表板

问题描述

我使用 api 创建了一个 http 发布请求,现在我遇到了一个小问题。注销表单后,我仍然可以访问主页而无需输入登录详细信息。即使在注销后会话也不会过期。这是我在登录控制器中使用的代码:

var app = angular.module('LoginApp');
app.controller('loginController', function($scope,$http,$rootScope,$window) {
    $scope.postdata = function () {
        var post = $http({
            method: "POST",
            url: "https://api-stg.martcart.pk/api/v1/user/login",
            dataType: 'json',
            data: JSON.stringify({
                userName: $scope.username,
                password: $scope.password
            }),
            headers: { "Content-Type": "application/json" }
        });
        post.success(function (data) {
            window.location='components/home/home.html';
               sessionStorage.setItem("authdata",JSON.stringify(data.token));
        });
        post.error(function () {
            alert("wrong credentials");
         });
    }
    $scope.logout = function(){
        // console.log("hello")
     window.location.href = 'http://localhost:5500/LoginAngularJS-API-master/index.html#/login';
     $window.sessionStorage.removeItem("authdata");
     
        //localStorage.removeItem("authdata");
        // $route.reload();
        // delete $window.sessionStorage;
        // $window.localStorage.clear();
        
    }
    
    
});

单击注销按钮后,将调用 logout.js 函数:

function logout() {
  
    window.location.href = 'http://127.0.0.1:5500/LoginAngularJS-API-master/index.html#/login';
    sessionStorage.removeItem("authdata");
    // sessionStorage.destroy();   
   
    // localStorage.removeItem("authdata");
    //    delete $window.sessionStorage;
    //         $window.localStorage.clear();
}

如果有人可以帮助解决问题,我会很高兴。非常感谢

标签: javascripthtmlangularjssession-variables

解决方案


您的代码看起来不错。也许试试sessionStorage.removeItem("authdata");

没有 $window。


推荐阅读