Tips for saving data in the $localStorage as an object

I need to store all the items in $localStorage like this:

$localStorage.userData.currentUser = data.name;
$localStorage.userData.devId= data.id;
$localStorage.userData.userRole = data.roles[0].name;
$localStorage.userData.userId = data.user_id;

Here is the controller code:

myApp.controller('loginController', ['$rootScope', '$scope', 'Auth', '$state', '$localStorage',
    function ($rootScope, $scope, Auth, $state, $localStorage) {

        function successAuth(res) {
            $localStorage.token = res;
            $scope.currentUser = $localStorage.token.name;
            console.log("res: ", res);

            Auth.setUserData(res, function(){
                $scope.error = 'No User data available';
            });


            if ($localStorage.token) {
                $state.go("dashboard");
                $scope.isLogin = true;
            } else {
                alert("Invalid username or password");
            }
        }

        $scope.signin = function () {
            var formData = {device_id: myip, platform: "WEB", provider: "EMAIL", uid: $scope.login.username, access_token: "", password: $scope.login.password};
            Auth.signin(formData, successAuth, function () {
                $rootScope.error = 'Invalid credentials';
                console.log($rootScope.error);
            });
        };

        $scope.isLogin = !angular.isUndefined($localStorage.token);
    }]);

I attempted the following based on the documentation, but it didn't work. It's showing an error saying '$storage' is undefined:

$scope.$storage = $localStorage;

$storage.userData.currentUser = data.name;
$storage.userData.devId= data.id;
$storage.userData.userRole = data.roles[0].name;
$storage.userData.userId = data.user_id;

How can I properly save all the data into $localStorage as mentioned above?

Answer №1

If you want to achieve this functionality, you could consider the following code snippet:

let userData = {
    userName : userDetails.name,
    userDevId : userDetails.id,
    role : userDetails.roles[0].name,
    userID : userDetails.user_id
 };

 localStorage.setItem( 'userData' , JSON.stringify(userData) );

Iterate through Local Storage items using a loop:

 for( let item in localStorage ) {

        // Parse each JSON string and push it into an array
        let parsedItem = JSON.parse( localStorage[item] );
        $scope.userData.push( parsedItem );

    }

To retrieve data based on its key:

localStorage.getItem( 'userData' );

Answer №2

check out this code snippet, you might find it useful:

 sessionStorage.setItem('account', JSON.stringify({
   username: "john_doe",
   balance: 500,
   bank: "XYZ Bank"
 }));
 account = JSON.parse(sessionStorage.getItem('account'));
 console.log(sessionStorage)

Answer №3

When working in the loginController, opt for utilizing $window over $localStorage. This can be achieved by using

$window.localStorage.getItem(...)
or
$window.localStorage["storage_name"]
.
In order to save data into the localStorage, simply execute
$window.localStorage['storage_name'] = angular.toJson(object_to_store)
;

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

transmit data retrieved from `getStaticProps` to other static pages in NextJS

While working on my project, I encountered the task of fetching a large JSON dataset from an external API within the getStaticProps function. This dataset needs to be divided into multiple parts and passed as props to numerous static pages (potentially hun ...

Unveiling the steps to automatically conceal a submitted form in React, no longer requiring the manual activation of a toggle button

Currently, I have a list of songs and a toggle button that reveals a form to add a new song. However, I want the form to hide automatically after submission without requiring another button click. I tried using useEffect but couldn't get it to work. A ...

Is it possible for a Jquery radio button to trigger an infinite loop?

When I click on a radio button, I want to receive an answer from the PHP file. However, when I use the radio button, the alert appears in an endless loop. Why does this happen and how can I make the alert display only once? I tried with just a regular but ...

The Iframe contains its own scroll feature within the body

I am facing an issue with displaying an Iframe inside a modal. The challenge is that the content within the Iframe varies in height, making it difficult to set a fixed height for the Iframe itself. When I try setting the height to 100%, the result is a 150 ...

organize a data set using react's hook system

Trying to sort an array using react hooks but the state is not updating. Any help on what could be going wrong? import React, { useState } from "react"; import ReactDOM from "react-dom"; import "./styles.css"; const dogs = [{ name: "fido", age: 22 }, ...

The length of the notification is determined by the ReadFlag

JS: function fetchNotifications(){ $.ajax({ url: "getgroupednotification.json", type: "GET", crossDomain: true, success:function(response){ ...

The length of the scope variable generates an error

var example = $scope.newgoal.gTitle; console.log(example.length); Even running this short code test, it throws an error message: TypeError: Cannot read property 'length' of undefined I've attempted to find various solutions without succes ...

Determine the name of the Java exception class using JavaScript

Here is the code I am using to call a Java web API: m$.ajaxq({ url: contextPath + "/updateElapsedTime", type: "POST", data: params, contentType: "application/json; charset=utf-8", dataType: 'text', async: optionalRunAsync, success: ...

Loop through an array of elements in JavaScript and retrieve the element with the largest pixel size

I am facing a challenge with elements positioned absolutely on a web page. My goal is to iterate over these elements and identify the one with the highest top value. I attempted two different approaches: const elems = document.querySelectorAll('.ind ...

What is the best way to customize the interval time for my specific situation?

I'm working on setting an interval in my app and I have the following code: HTML <div class="text"> {{currentItem.name}} </div> <ul> <li ng-repeat="item in items" ng-click="pickItem($index)">{{item.type}}</li> ...

Empty css file detected during gulp processing

My Gulp task is saving the CSS file with a size of 0kb. Here is the code snippet: Link to the code gulp.task('jpg', function () { gulp.src('./template/img/**/*.*') .pipe(changed('./dist/img/')) ...

Stopping a build programmatically in Next.js involves implementing specific steps that aim to halt

Is there a method to programmatically halt the execution of npm run build in Next.js when a specific Error occurs within the getStaticProps function? Simply throwing an Error does not seem to stop the build process. ...

Storing raw HTML in a Mysql database, then fetching and displaying it on a webpage

I'm having an issue with my application. It's a form builder that allows users to create their own forms and then save them for later use. The HTML code generated by the form builder is stored in a MySQL database. However, when I try to retrieve ...

Using Node.js and jQuery to retrieve a PDF from a server and showcase it on the frontend

I'm currently facing a roadblock. My goal is to retrieve all files (filenames) from a static folder along with its subfolders and display them on the front-end. Once a user clicks on one of the filenames, which are mostly PDFs, I want the server to r ...

The response from Moment.js shows the date as "December 31, 1969."

Currently, I am in the process of recreating one of FCC's backend projects: Upon testing my code, I noticed that when I input the following URL: http://localhost:3000/1 The result is as follows: {"unix":"1","natural":"December 31, 1969"} var e ...

CSS - owl carousel automatically stretches images to full width

Here is the code snippet that I am working with: $(document).ready(function() { $('.owl-carousel').owlCarousel({ loop:true, items:4, autoplay:true, autoplayTimeout:2000, autoplayHoverPause:true }); }); #owl-demo ...

Create a JavaScript array containing all the elements from a MySQL table

I am attempting to store my mysql table data in a JavaScript array. My goal is to push each element of the table into the array so that it looks like this: array[0] = [question: information01, answer: information02...] array[1] = [question: information11, ...

The intricacies of how Node.js handles asynchronous execution flow

I wanted to ask about the best approach for displaying data retrieved from MySQL. Do you think this workflow is correct? app.get('/demo/:id', function(req, res) { var query = csql.query('SELECT * FROM table_videos WHERE id=? LIMIT 1' ...

Problem: Implementing a horizontal scrolling feature using Skrollr

I'm interested in creating a horizontal animation controlled by skrollr. As I scroll down, I want the elements on my page to move from left to right within my container. When all elements have the same width, setting the scrolling data from 100% to 0 ...

Possible rephrased version: "Strategies to halt the playback of a screencast.com video that is

I recently uploaded a screencast video to my website and now I'm looking for a way to pause the video when I click on a button. I attempted using some JavaScript code with an onclick event attached to the button. var myVideoPlayer = document.getEleme ...