ngStorage in AngularJS app does not retain sessionStorage data

Hello everyone,

I am currently facing an issue with storing a user object in sessionStorage within my AngularJS application. Despite stepping through the code in debuggers like Chrome or FF, the sessionStorage does not seem to be getting set. Below is the code snippet from my angular service:

// Authentication/authorization Module
stonewall.authModule = angular.module("authModule", [
    // Module dependencies
    "ngStorage"
    ]);

// Authentication/authorization service tracks the current user
stonewall.authModule.service('authService', function ($localStorage, $sessionStorage) {

    // Initialize current user
    var currentUser = {};
    restoreSession();

    // Declare storage type-this may change if user selects
    // "Keep me signed in"
    var storageType = {};

    // Return the current user object
    this.getCurrentUser = function () {
        return currentUser;
    };
    // Returns whether there is a currently authorized user
    this.userAuth = function() {
        return currentUser.sid != "";
    };
    // Logout function, initializes the user object
    this.logout = function() {
        currentUser = {
            sid: "",
            status: 0,
            pswLastSet: 0,
            id: "",
            sigUID: "",
            sig: ""
        };
        //persistSession();
    };
    // Login
    this.login = function(user, subj) {
        if (user == null) return;
        currentUser = {
            sid: user.Principal.SId,
            status: user.Principal.ControlStatus,
            pswLastSet: new Date(user.Principal.PasswordLastSet),
            id: user.Identity.Id.DN,
            sigUID: user.Identity.Certificates[0].UID,
            sig: stonewall.hash(user.Principal.SId + subj.pswd),
        };
        persistSession();
    };
    // Persist to session storage
    function persistSession() {
        $sessionStorage.currentUser = currentUser;
    };
    // Restore session
    function restoreSession() {
        currentUser = $sessionStorage.currentUser;
        if (currentUser == null) {
            // Initialize to empty user
            currentUser = {
                sid: "",
                status: 0,
                pswLastSet: 0,
                id: "",
                sigUID: "",
                sig: ""
            };
        }
    };
});

Upon calling persistSession, I have verified in my FF debugging session that $sessionStorage contains the user data as expected.

However, when checking the DOM inspector, it appears that sessionStorage is empty...

Any assistance on resolving this issue would be greatly appreciated.

Answer №1

Have you considered the proper usage of angular's sessionStorage? In Angular, sessionStorage is a property of the $window object, so if you are not sure about your implementation, perhaps you have created your own service wrapper instead? I personally prefer using $window.sessionStorage and have showcased an alternative approach in this codepen example: http://codepen.io/chrisenytc/pen/gyGcx

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show a button instead of text based on the current status

I have a dynamic table displaying various data, mostly text, but with a few buttons included. Now, I need to figure out how to handle this Here is the current data structure: [ { "BET": 57630343, "CUSTOMER": 181645, "XX_FILL OPEN": true }, { "BET": 57 ...

Troubleshooting: AngularJS ngClick function malfunctioning with dynamically inserted HTML

In my app, there is a single input element with a mylist model. When mylist=1, I include first.html and when mylist=2, I include second.html. The issue arises when trying to change the value of mylist by clicking a button within each HTML template. To ach ...

Modifying the value of a variable causes a ripple effect on the value of another variable that had been linked to it

After running the code below, I am receiving values from MongoDB in the 'docs' variable: collection.find({"Stories._id":ObjectID(storyId)}, {"Stories.$":1}, function (e, docs) { var results = docs; results[0].Stories = []; } I ...

When a new component is loaded, React Martial UI component may face issues due to overwriting or

Currently, we are working on a vast web application that utilizes jquery and bootstrap. Our current task involves transitioning this extensive app to React with Material UI, piece by piece. As we progress towards transforming it into a React app, everythin ...

Assign a variable to a dynamic model within an AngularJS scope

I am facing an issue with scope closure. ... function(scope) { ... }); Within the scope, I need to achieve the following: $scope.favoriteTitle = 'some value' The challenge is that favoriteTitle cannot be static. It needs to be generated d ...

Verify if the array contains any empty elements

Is there a way to determine if an array contains empty elements? Consider the following array: var arr = [ 'a', 'b', , 'd']; In this case, arr[2] is undefined. It's important to check for such occurrences. One approach ...

Issue with timestamp in the Instagram API call to retrieve media using AJAX (GET /media/search)

My API call is returning a 400 bad request error message: {"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"invalid parameters-check the max\/min-timestamps, if you supplied them"}} Even though my request appears to be co ...

Adjust the background shade of a div according to the color attribute retrieved from a JSON data source

Looking at this snippet, I'm tasked with changing the color of the "header" div to match the color provided in the JSON data. The code snippet is as follows: $("#dropdown").change(function() { $("#header").css("background-color", $(this).val()); }).c ...

difficulty encountered when attempting to input multiple values into a single text field

There are four boxes containing values. When clicking on a box, the value should appear in a text field separated by commas if multiple boxes are selected. <li><a href="javascript:void(0)" onclick="check_stalls('A-14')" id="A-14">A-1 ...

Effective strategies for minimizing the bundle size of your NextJs application

Recently, I launched my first NextJS app and was surprised to see that the initial bundle size is around 1.5Mb, which seems quite large for me as a beginner in using Nextjs. I have shared an image of the yarn build and also my package.json. All the pages ...

Incorporating an HTTP-based IFRAME into an HTTPS web address

My situation involves a PHP application running in HTTPS mode, within which there is an iframe containing an HTTP file. Both the parent and the iframe exist within the same domain. Strangely, I am unable to access the iframe source using HTTP. Is there a ...

Is there a way to prevent the Alt+F4 function from closing tabs in the Internet Explorer browser

Ctrl+W and Alt+F4 can be used to close the IE browser, but I am looking to disable this default action. While I have found a way to handle the Ctrl+W command, I am struggling with disabling the Alt+F4 event. It seems that other Alt+Key events like Alt+En ...

Reboot the node.js server

As I delve into learning node.js, I decided to start with a basic example in a file named server.js: var http = require("http"); function onRequest(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("it&a ...

JQueryUI draggable multiple select containment

Hey everyone, I've managed to implement Jqueryui drag and drop along with Jqueryui selectable. One issue I'm facing is that when I select and move multiple objects, only the clicked element is contained within the parent while the others can move ...

Searching for multiple values using ng-model in AngularJS is a powerful feature that allows

I've looked everywhere for a solution to my problem but I haven't found an exact match. Can anyone lend a hand? Here's the ng-repeat filter list I'm working with: <ul> <li ng-repeat="f in filterOptions"> <p>{{f ...

Press the button to switch between displaying one component and hiding another component within reactjs

I am working on a project with two distinct buttons: one for grid view and another for list view. <button onClick={() => setClassName('jsGridView')} title="Grid View" > <IoGrid className="active" s ...

Prevent users from entering text and enable date and time selection by setting input date and time in angular-moment-picker to editable false, and add an icon for picking the date and time

Currently, I am utilizing the angular-moment-picker input for datetimepicker functionality. My goal is to make the input not editable to prevent users from manually entering text. Instead, I would like to add a button that allows users to click and open th ...

Is there JSON data available to determine the overall attendance rate in percentage?

I have a set of attendance data for a specific student. Each subject is marked with a 1 if the student was present, and a 0 if absent on a particular date. I need assistance in calculating the total attendance based on this information... { " ...

Developing an array-based multiple choice quiz

Being a complete novice, I am currently immersed in designing a multiple-choice quiz using arrays. The questions all follow a similar template: "Which word in the following has a similar meaning to '_________'." To implement this, I have created ...

Display highcharts in a separate window using ajax and jquery

I have come across similar inquiries but none with ajax and jquery, so I hope this is not a duplicate question. I am trying to load charts in a new window 'estadisticasMultiples.html', where there is a div with the tag charts. However, when I tr ...