Service object resets to default on f5 refresh

Issue

My service is working correctly but if I press f5(refresh), authservice dataUser values resets to default (basically to the values i give to dataUser in the service) even though when someone logs in successfully i set their values with setValues function (and working correctly before a refresh). Causing this isLoogedIn false and cant access any route, because for my if statement in app js

Here is my service:

function(){
angular.module('statusTrackAppApp').service('authService',authService);

function authService(){

    var dataUser={
        isLoggedIn:false,
        username:null,
        firstname:null,
        role:null
    };

    function setValues(isLoggedIn,data){
        dataUser.isLoggedIn=isLoggedIn;
        dataUser.username=data.username;
        dataUser.firstname=data.firstName;
        dataUser.role=data.role;
    };

    function getValues(){
        return dataUser;
    };

    return{
        setValues:setValues,
        getValues:getValues
    }
}

})();

This is my app.js

(function () {
'use strict';

angular
  .module('statusTrackAppApp', [
    'angular-jwt',
    'ui.router',
    'datatables',
    'ngModal',
    'ngFileUpload',
  ])
  .run(run)
  .config(function ($httpProvider,$stateProvider,$urlRouterProvider) {
    $stateProvider
  .state('login', {
    url: '/login',
    templateUrl: 'views/login.html',
    controller: 'loginController',
    controllerAs:'loginController',
    authenticate:false
  })
  .state('accessDenied', {
    url: '/accessDenied',
    templateUrl: 'views/accessDenied.html',
    authenticate:false
  }
  .state('retenciones',{
    url:'/retenciones',
    templateUrl: 'views/retenciones.html',
    controller: 'retencionesController',
    controllerAs:'retencionesController',
    authenticate:true
  });
  $urlRouterProvider.otherwise('/login');
  })
  .value('apiPath','http://localhost:3000/api/');

  function run($rootScope,$state,authService) {
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {  

      //if I press f5 i redirect to the login page because isLoggedIn becomes false, basically because dataUser.isLoggedIn resets to default, though it was originally true when someone logged in


      if (toState.authenticate && !authService.getValues().isLoggedIn) {
        event.preventDefault();
        $state.transitionTo('login');
      }
      if(toState.role && (!toState.role.includes(authService.getValues().role))){
        event.preventDefault();
        $state.transitionTo('accessDenied');
      }
    });
  }
})();

Hope I explained myself, english its noy my main language (sorry for that).
Any help? Thanks btw

Solution

Every time you reset the state of your Single Page Application, every AngularJS Service/Value is reset as well.

So, you need to rely on browser Session Storage (or Local Storage, but, since you need to store session-related data, Session Storage is a better choice).

As usual, it is better to look for an AngularJS library that wraps browser capabilities (with fallbacks, if needed), like ngStorage.

function() {
  angular
    // add dependency
    .module('statusTrackAppApp', ['ngStorage'])
    .service('authService', authService);

  // inject the appropriate storage service
  function authService($sessionStorage) {

    // load data
    var dataUser = $sessionStorage.dataUser || {
      isLoggedIn: false,
      username: null,
      firstname: null,
      role: null
    };

    function setValues(isLoggedIn, data) {
      dataUser.isLoggedIn = isLoggedIn;
      dataUser.username = data.username;
      dataUser.firstname = data.firstName;
      dataUser.role = data.role;
      // save data
      $sessionStorage.dataUser = dataUser;
    }

    function getValues() {
      return dataUser;
    }

    return {
      setValues: setValues,
      getValues: getValues
    };
  }

})();

Answered By – Francesco Colamonici

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published