Exploring the retrieval of stored information from $localStorage within an AngularJS framework

I have been working on a MEAN app, and after a user successfully logs in, I want to save the returned user data in the localStorage of the browser for future use. I am using the ngStorage module for this purpose. Below is the code snippet from my LoginController:


function loginController($http, $location, $rootScope,$localStorage){
    var vm = this;
    vm.signIn = signIn;

 function signIn() {      
    $http({
        url: '/login',
        method: 'post',
        data: vm.login
    }).then(function(respond) { 
     if(respond.data){ 
        $localStorage.userData = respond.data;   
         var info = $localStorage.userData;         
        $rootScope.userInfo = info; 
         $location.path('/dashboard/'+respond.data._id);
      }else{
         $location.path('/');
        }

Now when I access $rootScope in another controller, I can get the value that is stored in $localStorage. Even in my Chrome browser's inspect tool, I can see that the data is stored in $localStorage. However, when I refresh my page, I notice that although the data still exists in the browser's localStorage, it becomes null in my $rootScope after refreshing the page. I would appreciate any suggestions on how to retain this data in the $rootScope even after refreshing the page.

Answer №1

Just like any JavaScript variable, $rootScope is destroyed upon reloading the location. Your localStorage data remains accessible throughout your application until it is destroyed, removed, or reset.

function loginController($http, $location, $rootScope, $localStorage) {
    var vm = this;
    vm.signIn = signIn;

    function signIn() {
        $http({
            url: '/login',
            method: 'post',
            data: vm.login
        }).then(function(respond) {
            if (respond.data) {
                $localStorage.userData = respond.data;
                var info = $localStorage.userData;
                $rootScope.userInfo = info;
                $location.path('/dashboard/' + respond.data._id);
            } else {
                $location.path('/');
            }
        });
    }

    function anyController($scope, $localStorage) {
        console.log($localStorage.userData);
    }
}

This code snippet shows an example where you redirect to the main state if there is no userData available, using $localStorage within the module run function.

angular.module("yourAppName")
  .run(function ($rootScope, $state,$localStorage) {
    $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
      if(toState.name == 'app') return;
      if (!$localStorage.userData){
        $state.transitionTo("app");
        event.preventDefault(); 
        return;
      }
    });
  });

Answer №2

When the app reloads, extract user information stored in local storage

app.run(function($rootScope){
  if(localStorage['userData'])
  {
    $rootScope.userData = JSON.parse(localStorage.getItem('userData'));
  }
});

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

Determine the instance's name as a string in JavaScript

Currently, I am utilizing Three.js in combination with javascript. Upon running the following line of code: console.log(this.scene.children[1]) I receive the following output in the console within Chrome: https://i.stack.imgur.com/6LBPR.png Is there a w ...

The function does not provide an output of an Object

I have two JavaScript classes, Controller.js and Events.js. I am calling a XML Parser from Events.js in Controller.js. The Parser is functioning but not returning anything: SceneEvent.prototype.handleKeyDown = function (keyCode) { switch (keyCode) { ...

Functionality that can be utilized repeatedly

I've been struggling to implement a feature for repeatable blocks in my web form. The issue I'm facing is that when I click the buttons, nothing happens even though they work fine when tested in the console. I've been stuck on this problem f ...

Can you provide me with instructions on how to create a toggle effect for a button using vanilla JavaScript?

Looking for guidance on creating a toggle effect with a button that switches between 2 images. I've managed to get it working with event listeners on btn2 and btn3, but can't seem to implement the 'toggle' effect on btn1. Any insights o ...

Manipulating a textarea in jQuery by inserting a string and selecting a specific portion of it

Just as seen on SO with the B button: **bold text** Including that bold text is automatically highlighted and the cursor is placed right before the b ...

Reproducing scripts in Google Tag Manager and React/Next applications

Currently, I am delving into the realm of Google Tag Manager and React + Next.js for the first time. This experience is proving to be quite intriguing as my familiarity with GTM is limited and my exposure to React is even less. Nonetheless, it's not a ...

Every character entered in JSP should trigger an instant retrieval of the corresponding string in the servlet

Having a JSP file that contains a text field: <form action="someServlet" method=post> <input type ="text" name="user" id="uname"> <button type="submit" id="submit">Submit</button> </form> When typing each letter in the JSP, ...

Develop a personalized mapping API with a unique image integration for website navigation

Currently, I am in the process of developing a website for my university that will allow users to easily locate all available free food options on campus. My goal is to create a platform where food providers can register their events, have them saved in a ...

The "Splash Screen Div" page displayed during transitions and page loading

Creating a "Splash Screen Div" for a loading page involves waiting until everything is loaded and then hiding or moving the div off screen. Below is an example: index.html <div id="loading-Div"> <div id="bear-Logo"> < ...

What causes the non-reachable part of the ternary operator to be evaluated prior to updating the state with setTimeout?

Check out my latest code snippet for a react component that renders a massive component. While the huge component is still rendering, a loading indicator will be displayed. import * as React from "react"; import ReactDOM from "react-dom"; import {HUGECom ...

Launching a centered pop-up window to display a submitted form message

I am attempting to create a page that displays a confirmation message in a center-aligned pop-up window after the user submits a form. I have managed to open the page in a pop-up window, but I am struggling to center the window using my current code (I pre ...

Utilize separate production environments for each client on the NodeJS server to ensure seamless operation and

After conducting extensive research, I have been unable to find a solution to my current problem. I am operating a Node server with multiple environments (dev, test, demo, prod). The server is deployed on a Linux server in the production environment via a ...

Do not expect false outcomes in unit testing of service methods

function logUserOut() { var url = "User/Logout"; httpService.post(url, {}, {}).then(function (success) { }, function error(error) { }); storageService.clearData(); httpSe ...

Adding data to a JSON object using AngularJS

When attempting to insert an object into a JSON object, I am encountering an issue where it duplicates the JSON object. Here is a breakdown of the scenario: <input type="text" style="width: 40% !important;" placeholder="Nom" class="input-sm" ng-model= ...

What is the process for updating a placeholder text after the user makes a guess or enters

My latest project involves creating a fun guessing game where players have to identify the driver based on the teams they have driven for. The game displays the number of guesses allowed and keeps track of how many attempts the player has made so far. For ...

Can someone guide me on how to retrieve data from a MUI table within a React project

Currently, I am retrieving data from a server in JSON format and looping through this data to display specific information. Everything is functioning as expected, but I'm encountering an issue with a Popover element that contains items with onclick ev ...

Can anyone help me get my carousel to work properly?

I am facing a carousel problem in my personal exercise project. I have gathered HTML, CSS, and JavaScript from the internet and am attempting to integrate them all together. //Sidebar script start $(document).ready(function () { var trigger = $(&apo ...

Having difficulty accessing response data and headers within an AngularJS interceptor

I have a custom API on my server that sends a unique header (let's call it "customHeader") in response to http://localhost:8081/my/test/api. Currently, I am attempting to access this custom response header from an interceptor written in angularJS: an ...

What are some effective ways of using the parent, before, and children selectors?

<table> <tr><td><input type="text" value="123"></td><td><input class="here" type="text"></td></tr> <tr><td><input type="text" value="333"></td><td><input class=" ...

The jQuery bookmarklet in the djangobyexample book is completely unresponsive

As I work my way through Django By Example, I came across a chapter where a jQuery bookmarklet is created within a Django app. This allows users to easily save jpg images from websites into their user profile area within the Django app. Although the tutor ...