RSS 2.0
Sign In
# Monday, January 26, 2015

Often we need to keep a client session state in our angularjs application.

This state should survive page refresh and navigations within the application.

Earlier we used ngStorage module but lately have changed our opinion, as we think it's over-engineered and is too heavy at runtime.

We have replaced it with a simple service that synchronizes sessionStorage once during initialization, and once before page unload.

Look at an example (session.html):

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Session</title>
  <style type="text/css">
    .ng-cloak { display: none; }
  </style>
  <script src="angular.js"></script>
  <script>
angular.module("app", []).
factory(
  "session",
  ["$window", function($window)
  {
    var session =
      angular.fromJson($window.sessionStorage.getItem("app")) || {};

    $window.addEventListener(
      "beforeunload",
      function()
      {
        $window.sessionStorage.setItem("app", angular.toJson(session));
      })

    return session;
  }]).
controller(
  "Test",
  ["session",
  function(session)
  {
    this.state = session;
  }]);
  </script>
</head>
<body ng-app="app" ng-controller="Test as test">
  <input type="text" ng-model="test.state.value"/>
  <a href="session.html?p=1">Page 1</a>
  <a href="session.html?p=2">Page 2</a>
</body>
</html>    

Source can be found at nesterovsky-bros/angularjs-api/services/session.html.

Monday, January 26, 2015 8:46:36 AM UTC  #    Comments [4] -
AngularJS | javascript | Tips and tricks
Wednesday, May 13, 2015 11:57:01 PM UTC
This looks good. I've ditched ngStorage too, for similar reasons. I can't believe a persistence solution isn't fundamental to angular- of course people are going to press reload/back.

Only concern I have with your approach is the reliance on "beforeunload". What if it doesn't run? (eg browser crash) Shouldn't we find a way to store the variables when the change? (eg using getters/setters).
Simon
Thursday, May 14, 2015 7:57:26 AM UTC
Simon,

It's possible to define properties like in Object.defineProperty(),
and screen values immediately to storage, but we decided to stay with
simplest solution, as it works rather well.

If you want to force save, then it's possible to expose a function
that you can call manually. This can address a critical cases.
Vladimir Nesterovsky
Monday, January 18, 2016 6:50:58 PM UTC
Hi,
tried to make a Service using the code above. Here my implementation:

"use strict";

(function () {
var sessionStorageService =
function ($window)
{
var session = angular.fromJson($window.sessionStorage.getItem("geoHostApp-session")) || {};
$window.addEventListener
(
"beforeunload",
function()
{
$window.sessionStorage.setItem("geoHostApp-session", angular.toJson(session));
}
)
return session;
}
angular.module('geoHostApp').factory('sessionStorageService', ["$window", sessionStorageService]);
}());

But as soon as I run this script in my index.html I get module load Errors. Unfortunately I cant see a Problem, but I am newbee. I made other Services for other purposes without Problems using the same template.
Maybe you can help me, thanks.

With best regards

Gerhard
Monday, January 18, 2016 7:23:33 PM UTC
I can only guess without sources and error messages.

1. You have error in code somewhere.
2. You test is locally in file system with IE or Edge. In this case it can happen that no sessionStorage object is available.
Please try Chrome, or deploy on web server and test.
Vladimir Nesterovsky
All comments require the approval of the site owner before being displayed.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview
Archive
<October 2019>
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789
Statistics
Total Posts: 366
This Year: 2
This Month: 0
This Week: 0
Comments: 226
Locations of visitors to this page
Disclaimer
The opinions expressed herein are our own personal opinions and do not represent our employer's view in anyway.

© 2019, Nesterovsky bros
All Content © 2019, Nesterovsky bros
DasBlog theme 'Business' created by Christoph De Baene (delarou)