How to keep session in multipage angular application?

All we need is an easy explanation of the problem, so here it is.

I am having single page application with user authentication and there is no problem sharing session information there.

However I have part of site where are static pages where I would like just to include session information (logged in user, or login form). How I can share session information between two apps?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I would recommend creating a service that wraps localStorage or other apis to store persistent data. Here is an example using a localStorage implementation.

This implementation is synchronous but if I would use websql like or even server db then I would refactor it to use promises to return the storage object.

Controller

var demo = angular.module('demo', [ 'appStorage' ]);

demo.controller('AppStorageController', [ '$scope', 'appStorage',
    function($scope, appStorage) {
      appStorage('MyAppStorage', 'myAppStorage', $scope);
    } ]);

HTML

<div ng-controller="AppStorageController">
  <p>Local Storage: {{myAppStorage}}</p>
  <p>
    Username: <input type="text" ng-model="myAppStorage.username"></input>
  </p>
  <p>
    Remember me: <input type="checkbox"
      ng-model="myAppStorage.rememberMe"></input>
  </p>
</div>

JS

angular.module('appStorage', []).factory('appStorage',
    [ '$window', function($window) {
      var appStorages = {};
      var api = undefined;

      if ($window.localStorage) {
        api = {
          set : function(name, value) {
            $window.localStorage.setItem(name, JSON.stringify(value));
          },
          get : function(name) {
            var str = $window.localStorage.getItem(name);
            var val = {};
            try {
              val = str ? JSON.parse(str) : {};
            }
            catch (e) {
              console.log('Parse error for localStorage ' + name);
            }
            return val;
          },
          clear : function() {
            $window.localStorage.clear();
          }
        };
      }
      // possibly support other

      if (!api) {
        throw new Error('Could not find suitable storage');
      }

      return function(appName, property, scope) {
        if (appName === undefined) {
          throw new Error('appName is required');
        }

        var appStorage = appStorages[appName];

        var update = function() {
          api.set(appName, appStorage);
        };

        var clear = function() {
          api.clear(appName);
        };

        if (!appStorage) {
          appStorage = api.get(appName);
          appStorages[appName] = appStorage;
          update();
        }

        var bind = function(property, scope) {
          scope[property] = appStorage;
          scope.$watch(property, function() {
            update();
          }, true);
        };

        if (property !== undefined && scope !== undefined) {
          bind(property, scope);
        }

        return {
          get : function(name) {
            return appStorage[name];
          },
          set : function(name, value) {
            appStorage[name] = value;
            update();
          },
          clear : clear
        };
      };
    } ]);

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply