Search code examples
javascriptangularjsfactoryangularjs-factory

Refresh Angular JS Factory without page Re-load


I'm accessing data stored in local storage through factory in angularjs. On page load the factory loads and accesses data from local storage and stores them in variables. I'm able to call that factory and fetch the value in the variables.

However whenever I call the factory after localstorage values have been changed the factory returns the old value instead of the new value. Is there a way to refresh the factory so that it again fetches the local storage values without refreshing the entire page?

Javascript Code..

headerApp.factory('userFactory', ['$rootScope', function($rootScope){
    var dataFactory = {};
    dataFactory.user = localStorage.getItem("valueA");
    dataFactory.userName = localStorage.getItem("valueB");
    dataFactory.userAccessToken = localStorage.getItem("valueC");
    return dataFactory;
}]);

On calling userFactory.user, userFactory.userName after a function changes localstorage values returns old values instead of new ones. Please Help


Solution

  • How about moving the code where you are pulling info from your local storage into a function in the factory, and then any time you update any of the local storage, you call that function to update the dataFactory too?

    headerApp.factory('userFactory', ['$rootScope', function($rootScope){
      var dataFactory = {};
    
      this.updateUser();
      this.updateUserName();
      this.updateAccessToken();
    
      updateUser () {
        dataFactory.user = localStorage.getItem("valueA");
      }
    
      updateUserName () {
        dataFactory.userName = localStorage.getItem("valueB");
      }
    
      updateUserAccessToken () {
        dataFactory.userAccessToken = localStorage.getItem("valueC");
      }
    
      return dataFactory;
    }]);
    

    And then at any point, say the user name got changed on the local storage end, you can call this.userFactory.updateUserName(); to update dataFactory.userName.