页面刷新导致用户在角度js中自动注销

时间:2016-02-02 12:41:58

标签: javascript angularjs logout page-refresh

我有一个登录API,我在我的服务中使用它

 <div class="header-user-menu">
        <div ng-show="isUserLoggedIn() == false ">
            <a href="" ng-click="$state.go('app.sr.login')" class="">{{'HEADER.LOGIN' | translate}}</a>
            <!--<a ui-sref="app.sr.login" class="">{{'HEADER.LOGIN' | translate}}</a>-->
        </div>
        <div ng-show="isUserLoggedIn()" class="userName">{{'HEADER.WELCOME' | translate}} {{currentUser.emailAddress}}</div>

    </div>

在我的标题html中,我在登录时显示用户名 的 header.html中

(function() {
    'use strict';

    angular
        .module('safe-repository')
        .controller('AppLayoutCtrl', appLayoutCtrl);

    // Implementation of controller 
    appLayoutCtrl.$inject = ['$rootScope', '$scope'];

    function appLayoutCtrl($rootScope, $scope) {


        $scope.isUserLoggedIn = isUserLoggedIn;

        function isUserLoggedIn() {
            if ($rootScope.currentUser
                && $rootScope.currentUser.emailAddress != null
                && $rootScope.currentUser.emailAddress != '') {
                return true;
            }
            return false;
        }

    }
})();

和js文件在这里

logInToService

这里我有一个注册服务,我已经定义了function registrationService($rootScope, httpWrapperService, $modal, $state, $cookieStore) { var self = this; // expose functions self.hasUserAccessToLevel = hasUserAccessToLevel; self.logInToService = logInToService; self.getCurrentUserToken = getCurrentUserToken; self.showRegistrationViewForLevel = showRegistrationViewForLevel; self.currentUser = { //emailAddress: '', //password: '', //token: '' } $rootScope.currentUser = null; self.currentUserToken = null; function logInToservice (------){----}})(); 方法

XmlTextReader

问题是,每当用户按下页面刷新F5时,用户就会被注销。即使我试图将数据存储在localstorage中,但实际上我并没有得到控制流。

2 个答案:

答案 0 :(得分:7)

您正在尝试将数据保存到localStorage,但您没有阅读它。 您拥有用户数据的currentUser变量是一个常规的javascript变量,在您重新加载页面时会重置该变量。

你需要做这样的事情:

// ...
// user logs in, remember it into the local storage
// Note: is is better to use it via $window.localStorage
$window.localStorage.setItem('user', JSON.stringify(user));
this.currentUser = user;

//...
// function to get the user, if this.currentUser is not set,
// try to load from the local storage
getUser: function() {
  if (this.currentUser) {
      return this.currentUser;
  }
  var storageUser = $window.localStorage.getItem('user');
  if (storageUser) {
    try {
      this.user = JSON.parse(storageUser);
    } catch (e) {
      $window.localStorage.removeItem('user');
    }
  }
  return this.currentUser;
}

// you may also want to remove the user data from storage when he logs out
logout: function() {
    $window.localStorage.removeItem('user');
    this.currentUser = null;
},

答案 1 :(得分:0)

您需要创建一个登录会话,以便在页面刷新后不会注销。看看这个链接:

http://maffrigby.com/maintaining-session-info-in-angularjs-when-you-refresh-the-page/