How to access localStorage within an AngularJS module

Upon successful login, I save the user's data in the localStorage and redirect them to the Dashboard. LoginCtrl:

    (function() {
    'use strict';

    angular.module('BlurAdmin.pages.login')
        .controller('LoginCtrl', LoginCtrl);

    /** @ngInject */
    function LoginCtrl($scope, $timeout, $http, $location, toastr) {

        $scope.login = function() {

            var data = { email: $scope.email, senha: $scope.password }

            $http.post('http://xxxxxxx/snaapp/admin/login', data).
            then(function(response) {
                localStorage.token = response.data.token;
                $http.get('http://xxxxxxx/snaapp/auth/user/info', { headers: { 'Authorization': response.data.token } }).
                then(function(response) {

                    //Set values in localStorage

                    localStorage.user = JSON.stringify(response.data);
                    $location.path("/dashboard");
                }).catch(function(fallback) {
                    toastr.error('Error logging in');
                });

            }).catch(function(fallback) {
                toastr.error('Error logging in');
            });
        };

    }
})(); 

How can I access data stored in the localStorage within a specific module?

    (function() {
    'use strict';

    angular.module('BlurAdmin.pages.juridico', [
            'BlurAdmin.pages.juridico.acoesColetivas'
        ])
        .config(routeConfig);

    /** @ngInject */
    function routeConfig($stateProvider) {

        //I would like to do something similar to this:
        console.log(localStorage.user)

        $stateProvider
            .state('juridico', {
                url: '/juridico',
                template: '<ui-view  autoscroll="true" autoscroll-body-top></ui-view>',
                abstract: true,
                title: 'Jurídico',
                sidebarMeta: {
                    icon: 'ion-gear-a',
                    order: 100,
                },
            });
    }

})();

The above code works only when the page is reloaded, but I need to access this data in the module without reloading the page.

Answer №1

Storing data in local storage

const userInformation = JSON.stringify(response.data);
localStorage.setItem("userData", userInformation);

Retrieving data from local storage

const retrievedUser = localStorage.getItem("userData");

More information available at: link

Answer №2

To access local storage in your Angular controller, make sure to inject $window and use $window.localStorage.

You can verify the stored data by navigating to Chrome -> F12 -> Application -> Storage -> Local Storage.

(function() {
  'use strict';

  angular.module('BlurAdmin.pages.login')
    .controller('LoginCtrl', LoginCtrl);

  /** @ngInject */
  function LoginCtrl($scope, $timeout, $http, $location, toastr, $window) {

    $scope.login = function() {

      var data = {
        email: $scope.email,
        password: $scope.password
      }

      $http.post('http://xxxxxxx/snaapp/admin/login', data).
      then(function(response) {
        $window.localStorage.token = response.data.token;
        $http.get('http://xxxxxxx/snaapp/auth/user/info', {
          headers: {
            'Authorization': response.data.token
          }
        }).
        then(function(response) {

          //Store user data in localStorage

          $window.localStorage.user = JSON.stringify(response.data);
          $location.path("/dashboard");
        }).catch(function(error) {
          toastr.error('Error logging in');
        });

      }).catch(function(error) {
        toastr.error('Error logging in');
      });
    };

  }
})();

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

send multiple textbox values to controller in CodeIgniter

I am new to Codeigniter and I'm facing some difficulties in understanding how to accomplish a task. In my view page, there are five rows generated using a for loop. Each row consists of two select boxes and two input boxes. I don't know how to re ...

Skip a single test from a suite in Firefox using Protractor automation framework

I have a collection of tests in my tests folder, all named with the convention ending in spec.js. By using the */spec.js option in the Config file, I am able to run all tests seamlessly. However, I encountered an issue where I needed to skip running a spe ...

Button Fails to Respond on Second Click

I have a button that triggers a JavaScript function. This function, in turn, initiates two sequential AJAX calls. Upon completion of the first call, it performs some additional tasks before proceeding to the second AJAX call. The button functions correctl ...

Connecting users from a mobile website to a particular item within the Amazon application

Recently, I've been working on linking from my mobile site to a particular item within the Amazon app. My JavaScript code includes a try/catch block that redirects users to the webpage if they don't have the app installed. However, I've foun ...

Tips for gathering all links from a JSON object

When dealing with a JSON object of any structure, simple or complex, what would be the most efficient way to extract all URLs from the data and store them in an array for iteration in JavaScript? { "url": "https://example.com:443/-/m ...

Vue: Choosing an option during the execution of setInterval

I'm facing an issue where I can't select an option while a setInterval function is running on the page. The main problem is that an option cannot be selected at the same time as the setInterval timer fires. let updateDelay = 100; var vueObj = ...

I successfully linked expressjs, nodejs, reactjs, and mysql in my project. I'm puzzled as to why everything runs smoothly after I restart my express server, but encounters issues when I refresh the page

express path users.js var express = require('express'); var router = express.Router(); const connection = require('./MySQL.js') /* Accessing user data. */ router.get('/', function(req, res, next) { connection.connect() ...

Warning: Non-power of two image detected in Three.js

Encountering an issue with a warning in three.js that says: THREE.WebGLRenderer: image is not power of two (600x480). Resized to 512x512. Attempted to resolve it by adding THREE.LinearFilter, but no luck. var texture = new THREE.TextureLoader().load(data[ ...

Utilizing onmouseover and onmouseoff events with images to dynamically alter text content

I have 6 images and I want to dynamically change the text next to them based on which image is being hovered over with the mouse. Even though I attempted to achieve this using JavaScript with the onmouseover and onmouseout events, my code doesn't see ...

In Angular.js, there is a limitation with ng-keyup where event.preventDefault() cannot be utilized, and ng-keypress may have delays when updating the value for an

Issue: The input type number with min and max constraints is not being enforced while typing in the input box. It allows values outside of the specified range to be entered. However, using the arrow buttons of the input type number works fine. Solution Ne ...

Fade in an image using Javascript when a specific value is reached

Here's the select option I'm working with: <div class="okreci_select"> <select onchange="changeImage(this)" id="selectid"> <option value="samsung">Samsung</option> <option value="apple">App ...

Issue with undefined arrays in the Angular merge sort visualization tool

I am currently working on developing a visualizer for sorting algorithms using Angular. However, I have encountered some difficulties while implementing merge sort. As a Java programmer, I suspect that there may be an issue with my TypeScript code and the ...

Leveraging PapaParse for CSV file parsing in a React application with JavaScript

I am encountering an issue with reading a CSV file in the same directory as my React app using Javascript and Papaparse for parsing. Below is the code snippet: Papa.parse("./headlines.csv", { download: true, complete: function(results, f ...

Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed t ...

Is AngularJS causing issues with Foundation modals? Any solutions to this problem?

Wondering how to manage Foundation4 modals with AngularJS? I've noticed that when I navigate from a modal to a new view, the old modal disappears but the page stays darkened as if it's still there in the background. I tried adding a class attribu ...

Learn the process of appending an item to a list using Vue.js

Recently starting with vue.js and facing an issue: data: { ws: null, newMsg: '', username: null, usersList: '' }, created: function() { var self = this; this.ws = new We ...

requesting data and receiving a promise object

I developed a function called getCartItems that invokes getSingleItems with the ID as an argument. When I log the JSON result in getSingleItem, it correctly displays the product object. However, when I try to access the function call value, I am getting a ...

Using JQUERY to create a smooth sliding transition as images change

Currently, I have set up three images (1.jpg, 2.jpg, 3.jpg) along with an image using the code: <img id="add" src="1.jpg"></img>. The width, height, and position of this additional image are adjusted as needed and are functioning correctly. Fur ...

Verify the authenticity of a date using the locale parameter in the Intl API

Seeking advice for validating inputfield based on locale argument. How to format dates differently depending on the specified locale? For example, if locale is 'en-uk' then date should be in mm/dd/yyyy format, but if locale is 'de-ch' i ...

What method can I use to replace the status bar from the top?

Is there a way to smoothly slide in and out a <View/> on React Native iOS, similar to the animation sequences shown in the images below? ...