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

Using AngularJS controllers: How can one trigger a controller from within a different controller?

Within my script, I have a list controller defined as follows: define([ 'jquery', 'app' ], function ($,app) { app.controller("ListContacts", function($scope,$route,$http){ $http({ method: 'GET&apo ...

Utilizing a form on numerous occasions prior to its submission

As a newcomer to JavaScript, I am exploring the best approach for a specific task. The task involves a form with checkboxes representing different music styles and a selector for names of people. The goal is to allow users to select music styles for mult ...

Performing multiple queries simultaneously in AngularJS

Looking to create a page using AngularJS that displays information from two tables. Table 1 : StateList StateCode StateName AZ ARIZONA CA CALIFORNIA ...

Bringing tex2max.js into an angular application using npm and index.html

Every time I attempt to import tex2max with the command declare var tex2max: any;, I encounter a ReferenceError: tex2max is not defined. Interestingly, this issue does not arise with other npm packages. Despite trying various methods such as installing the ...

Utilizing Vuetify 2 skeleton-loader to customize loading states through Vuex store manipulation

Utilizing the Vuetify v-skeleton-loader component to wrap a v-data-table component. The server-side pagination and sorting in the data-table component are set up. To enable server-side pagination, the documentation recommends monitoring the options objec ...

What is the significance of curly braces within function parameter declarations in JavaScript?

Recently, I have been exploring a tutorial that delves into setting up React with Redux. While following along, I came across some unfamiliar syntax involving curly braces within function parameter definitions. Can someone explain what purpose these serve? ...

Leveraging jQuery plugins within an AngularJs application

I am currently trying to implement the tinyColorPicker plugin from here in my Angular app, but I am facing difficulties with it. An error message keeps appearing: TypeError: element.colorPicker is not a function In my index.html file, I have included th ...

Is there a PHP script available to verify the status of FTP servers and determine if

I am in need of creating a PHP script that is triggered by a setInterval("ajaxrequest('ftp.php', 'context')", 1000) function. The PHP script itself is quite simple. It consists of an array containing FTP addresses. The script loops thro ...

`On mouseup event, changing specific text`

I've been working on a real-time HTML highlighter that surrounds selected text with span elements containing a background property. Check out the fiddle here: https://jsfiddle.net/4hd2vrex/ The issue arises when users make multiple selections, leadi ...

Is there a way to use Lodash to quickly return the same value if a condition is met using the ternary operator

Is there a condensed way to do this using Lodash? (or perhaps Vanilla JS/TypeScript) var val = _.get(obj, 'value', ''); Please note that var val = obj.value || ''; is not suitable as it considers 0 and false as valid but fal ...

Sending a post request from JavaScript to Django Rest Framework

I am working with a DFR api endpoint: url = http://example.com/api/data/ The URL of the page where I am running JavaScript code is: http://example.com/page/1/ I have logged in as User1 in my browser. POST request - from DRF browser API - successful. G ...

Unusual Glitch in Bootstrap 3 Dropdown Menu

I am currently developing a website using Bootstrap 3. I am encountering an issue with the navbar dropdown. When I click on the link, it changes to show "expand child menu" and "collapse child menu". To clarify, here is the image I am referring to: Initi ...

An error has occurred with the Firefox Addon: the module `path` cannot be located within the resource://gre/modules/commonjs/http.js

Currently developing a Firefox add-on on Windows10 with node v5.8.0 and npm v3.5.3, using Firefox v.45.0 The issue arises from the following line of code: var path = require("path"); The error message reads: Message: Module `http` is not found at resou ...

When using JavaScript to dynamically load canvases and create drawing contexts within a function, the context may suddenly disappear

Currently, I am modifying the canvases displayed through ajax calls and also updating what is drawn on each canvas. The primary issue I am facing is that my main drawing function fails on getContext and there are some unusual behaviors such as missing canv ...

Show the "Splash" picture, then switch to a newly uploaded image and show it for a set amount of time

I am in the process of developing an HTML/JavaScript page that will showcase a splash image (splash.jpg) until it gets replaced by another image file called latest.jpg. Once this latest.jpg is displayed, I want it to remain on the screen for 90 seconds bef ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...

Printing keys of objects in an array in AngularJS through iteration

Here is an array of objects that I am attempting to iterate in ng-repeat and print keys, but I am facing some challenges. $scope.directivesInfo = [ {"ngRepeat": {"enter": true, "leave": true, "move": true, "add": false, "remove": false}}, {"ngView ...

What could be causing my Vue.js sorting array script to malfunction?

I'm encountering an issue with sorting the table by Date. The sort function used to determine the type of sorting no longer works, and I'm unsure why. html: <th @click = "sort('data_produktu')" class="date">Da ...

Angular blocking interface version 0.2.2 encountered a problem with the error message "Unable to access property 'blockUI' of null"

I'm facing an issue with the Angular block UI version 0.2.2 that I added. It's not functioning properly and showing the following error: Cannot read property 'blockUI' of null Error displayed in console: Code snippet: sampleclick( ...

The JWT authentication token functions perfectly in Homestead environment, but encounters issues when deployed to the live

Let's talk about a unique scenario I'm facing. I have an app built with ionic, utilizing "satellizer" and "angular-jwt" to interact with a backend powered by Laravel5, integrated with barryvdh/laravel-cors and tymondesigns/jwt-auth. This setup fu ...