8

I have a Login API which I am using it in my service

function logInToService(callback, errback, login, password, rememberLogin) {
            var url = "User/Login";

            var authorizationHeader = {'Authorization': "Basic " + login + ":" + password};
            httpWrapperService.post(url, {login: login, password: password}, authorizationHeader).then(
                function success(loginToken) {
                    // transform data here

                    self.currentUser.emailAddress = login;
                    self.currentUser.password = password;
                    // store token in a cookie
                    self.currentUser.token = loginToken;
                    $rootScope.currentUser = self.currentUser;


                    if (rememberLogin) {

                        localStorage.userName=login;
                        localStorage.password=password;
                    }

                    httpWrapperService.setAuthenticationToken(loginToken);
                    callback(loginToken);
                },
                function error(errorObject) {
                    errback(errorObject);
                }
            );
        }

And in my header html I am displaying the user name on top when he gets logged in Header.html

 <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>

and js file is here

(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;
        }

    }
})();

and here I have one registration service where I have defined logInToService method

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 (------){----}})();

The problem is that every time when user presses page refresh F5 , user gets logged out. Even though I am trying to store the data in localstorage , but actually I am not getting the flow of control.

abidibo
  • 4,175
  • 2
  • 25
  • 33
shreyansh
  • 1,637
  • 4
  • 26
  • 46

2 Answers2

7

You are trying to save the data into localStorage, but you are not reading it. The currentUser variable you have the user data in is a regular javascript variable which gets reset when you reload the page.

You need to do something like this:

// ...
// 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;
},
Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54
0

you need to create a session for login so that it does not log out after page refresh. have a look at this link:

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

Ankush Rishi
  • 2,861
  • 8
  • 27
  • 59
  • Actually the problem is registrationService is getting reloading and because of that , $rootScope.currentUser is setting to null – shreyansh Feb 02 '16 at 13:47