如何使用angularjs注销后清除本地存储

时间:2015-12-14 09:38:23

标签: angularjs

Html代码

<div><a href="#/logout"><h2>Log Out</h2></a></div>

我的路由

 app.config([ '$routeProvider', function($routeProvider) {

    $routeProvider.when('/', {
        templateUrl : 'app/components/login/Login.html',
        controller : 'loginCtrl'

    }).when('/register/', {
        templateUrl : 'app/components/register/register.html',
        controller : 'registerController'
    }).when('/welcome/', {
        templateUrl : 'app/components/welcome/welcome.html',
        controller : 'welcomeController'
    }).when('/home', {
        templateUrl : 'app/components/home/home.html',
        controller : 'homeController'
    }).when('/homeView', {
        templateUrl : 'app/components/home/homeView.html',
        controller : 'homeController'
    }).when('/graph', {
        templateUrl : 'app/components/home/graphView.html',
        controller : 'LineCtrl'
    }).when('/logout', {
        templateUrl : 'app/components/login/Login.html',
        controller : 'logoutCtrl'
    }).otherwise({
        redirectTo : "/"
    });
} ]);

退出控制器

app.controller('LogoutController',function($location,$scope){
        $location.path('/');
});

它工作正常,退出后进入登录页面,如果我按下后退按钮也不会重定向到最后一页,但我认为这不是正确的方式我正在工作,我不是在注销时清除本地存储,我坚持如何通过注销清除本地存储值,请帮助我,我是angularjs的新手

登录控制器,其中值设置为localstorage

 $scope.login = function () {
         $scope.empData=[]

         $scope.empData = loginService.get('http://183.1.1/HospitalManagementSystem/Service1.svc/LoginVerification/' + $scope.emailId + '/' + $scope.password);

         $scope.empData.then(function (empData) {
             console.log( $scope.empData)
             /*if (empData !== undefined && empData !== null){
                 if(empData._statusCode === constants.statusCode) {*/
                     if (empData.LoginVerificationResult.length === 0) {
                        console.log('Employee details are not Available');
                     } else {
                         $rootScope.name=empData.LoginVerificationResult[0].UserName;


                         localStorage.setItem("Role ID",empData.LoginVerificationResult[0].RoleID);
                         localStorage.setItem("UserId",empData.LoginVerificationResult[0].UserId);
                         localStorage.setItem("UserName",empData.LoginVerificationResult[0].UserName);                      
                                   $location.path('/welcome')
                     }
         });
     };

LoginService

app.service('loginService', [ '$http', function($http) {

    this.get = function(path) {
        var data = $http.get(path).then(function(response) {
            return response.data;
        });
        return data;
    };

} ]);

1 个答案:

答案 0 :(得分:16)

我认为你只需要在注销控制器中使用localStorage.clear();

app.controller('LogoutController',function($location, $scope, $window){
    $window.localStorage.clear();
    $location.path('/');
});