Storing a string in localStorage versus $localStorage in Angular 1 yields distinct value differences

I have encountered an issue in my angular controller where I am trying to save a token returned from an API endpoint as a string. In this example, I have used the variable testData instead of the actual token.

var testData = "testdata"

$localStorage['jwtToken'] = testData
localStorage.setItem('jwtToken',testData)

Here is what is stored for the first line:

{"ngStorage-jwtToken" : ""testdata""}

And now for the second line:

{"jwtToken" : "testdata"}

The key changing makes sense to me, but I'm puzzled by the double quotes surrounding the data string in the value of the key in the first line. Has anyone faced this issue before? Is there something wrong with my approach?

Below is the code snippet:

angular.module('app', [
  'ngAnimate',
  'ngAria',
  'ngCookies',
  'ngMessages',
  'ngResource',
  'ngSanitize',
  'ngTouch',
  'ngStorage',
  'ui.router'
]);

app.controller('SigninFormController', ['$scope', '$http', '$state', '$localStorage',
  function($scope, $http, $state, $localStorage) {
    $scope.user = {};
    $scope.authError = null;
    $scope.login = function() {
      $scope.authError = null;
      // Attempting to login
      $http.post('api/auth/login', {
          email: $scope.user.email,
          password: $scope.user.password
        })
        .then(function(response) {
          if (response.status = 200 && response.data.token) {

            var testData = "testdata"

            $localStorage['jwtToken'] = testData
            localStorage.setItem('jwtToken', testData)

            /*
                $localStorage['jwtToken'] = response.data.token
                localStorage.setItem('jwtToken',response.data.token)
                */

            $state.go('app.home');
          } else {
            $scope.authError.message
          }

        }, function(err) {
          if (err.status == 401) {
            $scope.authError = err.data.message
          } else {
            $scope.authError = 'Server Error';
          }
        });
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>

<body ng-controller="">
  <div class="container w-xxl w-auto-xs" ng-controller="SigninFormController">

  <div class="m-b-lg">
    <div class="wrapper text-center">
      <strong>Sign in to get in touch</strong>
    </div>
    <form name="form" class="form-validation">
      <div class="text-danger wrapper text-center" ng-show="authError">
        {{authError}}
      </div>
      <div class="list-group list-group-sm">
        <div class="list-group-item">
          <input type="email" placeholder="Email" class="form-control no-border" ng-model="user.email" required>
        </div>
        <div class="list-group-item">
          <input type="password" placeholder="Password" class="form-control no-border" ng-model="user.password" required>
        </div>
      </div>
      <button type="submit" class="btn btn-lg btn-primary btn-block" ng-click="login()" ng-disabled='form.$invalid'>Log in</button>
      <div class="text-center m-t m-b"><a ui-sref="access.forgotpwd">Forgot password?</a></div>
      <div class="line line-dashed"></div>
      <p class="text-center"><small>Do not have an account?</small></p>
      <a ui-sref="access.signup" class="btn btn-lg btn-default btn-block">Create an account</a>
    </form>
  </div>
  <div class="text-center" ng-include="'tpl/blocks/page_footer.html'">
  
  </div>
</div>
</body>

Answer №1

Reason for enclosing string in double quotes

To easily extract the correct object, array, or string from storage without having to determine the types, developers often encapsulate the data within double quotes. This allows them to utilize JSON.parse() method effectively.

Here is a basic representation:

localStorage.setItem('xxx', '"testData"');
var val1 = JSON.parse(localStorage.getItem('xxx'));

localStorage.setItem('yyy', '{"foo": "bar"}');
var val2 = JSON.parse(localStorage.getItem('yyy'));

Purpose of prepending the key name with 'ngStorage'

By adding 'ngStorage' at the beginning of the key names, developers can differentiate between Angular-specific keys and other keys in localStorage. This way, they can easily iterate over the keys and populate their objects accordingly.

var myStorage = {};
Object.keys(localStorage).forEach(function(key){
    if (key.indexOf("ngStorage")===0) {
       myStorage[key.substr(10)] = JSON.parse(localStorage[key]);
    }
});

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

Leverage regular expressions to extract numbers preceding the final matched instance

Within my string of logs, I have the following: rgb(255, 255, 255) 0px 0px 0px 16px inset I am interested in extracting the dynamic value, which in this case is 16. How can I create a regex pattern that will capture the last instance of px, and then retr ...

Running a designated AJAX function from a variable by utilizing Applescript

Struggling to execute a JavaScript code within a page using Applescript. In the JavaScript, an AJAX function was defined like so: var myFunction = function () { // Here be the code... } I attempted this in Applescript: do JavaScript "document.myFunct ...

Using TypeScript, you can replace multiple values within a string

Question : var str = "I have a <animal>, a <flower>, and a <car>."; In the above string, I want to replace the placeholders with Tiger, Rose, and BMW. <animal> , <flower> and <car> Please advise on the best approach ...

Is there a way for me to showcase the latitude and longitude retrieved from JSON data on a Google Map using modals for each search result in Vue.js?

After receiving JSON data with search results, each containing latitude and longitude coordinates, I am attempting to display markers on a Google map modal when clicking "View Map". However, the code I'm using is not producing the desired outcome. Th ...

jQuery failing to transmit JSON in AJAX POST call

I'm a bit perplexed at the moment, as I'm attempting to send data to my Node.js server using the code snippet below: $.ajax({type:'POST', url:'/map', data:'type=line&geometry='+str, succe ...

Can "Operator" be used as a function parameter?

Take a look at this code snippet: const myFunction = (x, y, z) => { //Some code here }; $('whatever').on( event, function(){ myFunction( event.originalEvent && event.originalEvent.target ); //What is this operator doing? }); Can yo ...

Loop through the JSON data and dynamically display corresponding HTML code based on the data

I've developed a survey application using React, where I initially wrote code for each question to display radio buttons/inputs for answers. However, as the survey grew with multiple questions, this approach resulted in lengthy and repetitive code. To ...

Tips for extracting information from a Javascript Prompt Box and transferring it to a PHP variable for storage in an SQL database

My current issue involves a specific function I want my script to perform: before a user rejects an entry on the server side, the system needs to prompt a text box asking for the reason behind the rejection. The inputted reason should then be saved to a My ...

Adding a CSS class to a Vue component with a custom prop

I am looking to create a custom component in Vue that has the following props: text = the text to display in the link. icon = the identifier of the icon to display next to the link. < sidebar-link text="Home" icon="fa-home"> Below is the .Vue ...

Console.log() will not display any JSON duplicates

My JSON data structure is pretty flat and can have duplicate attributes. I built a logic to remove the duplicates but when testing it out, something strange happened. The logic was always counting the attributes once, resulting in no duplicates. To test th ...

Creating a type definition for the createSelector function based on the useQuery result

Struggling to find the correct typings for the createSelector res parameter from redux-js, especially in TypeScript where there are no examples or explanations available. The only guidance is provided in JS. const selectFacts = React.useMemo(() => { ...

Baking delicious cookies with the help of AngularJS

I am looking to implement a way to store user input data in a cookie that will persist even after the session ends. I have tried using local storage before, but encountered issues with it being overwritten on each submission. Can anyone provide guidance ...

The NetSuite https.post() method is throwing an error that reads "Encountered unexpected character while parsing value: S. Path '', line 0, position 0"

I'm currently facing an issue when trying to send the JSON data request below to a 3rd party system using the "N/https" modules https.post() method. Upon sending the request, I receive a Response Code of "200" along with the Error Message "Unexpected ...

What is the method for assigning a value to a JSON object using data from another JSON object?

I am faced with the task of setting the seqNo property in one JSON object, b, based on the id from another JSON object, a. How can I achieve this? var a = [{id: "Make", seqNo: 4}, {id: "Model", seqNo: 1}, {id: "XModel", seqNo: 2 ...

Limit the ng-repeat results based on search input using a transformation filter

I am currently working with an array of records that are being displayed in an HTML table with filters in the header. However, I have encountered an issue where some values are transformed by filters, causing the ng-repeat filter to fail. <table class= ...

Verify the ng-if condition for a specific value and display an alternative option if the condition is not

When obtaining a response from the server in JSON format (containing color.mix and color.pure), it is passed directly to the template. In this template, I need to display a value if it exists or show another value if it does not. <span ng-if="color.mix ...

Exploring the implementation of window.addEventListener within an Angular project

I am currently working on testing a method in Angular using Jasmine. However, I am running into an issue with triggering the mouse event (specifically when the browser back button is clicked). Below is the code snippet I'm working with: navigate() { ...

The submit option fails to appear on the screen in the JsonForm library

I've been using the JsonForm library ( https://github.com/jsonform/jsonform ) to define a form in HTML. I have set up the schema and form of the JsonForm structure, but for some reason, the "onSubmit" function that should enable the send button is not ...

What is the best way to apply the active class using ng-click?

Here is an example of code I am working with: <div class="account-item"> <div class="account-heading" ng-class="active"> <h4 class="account-title"> <a href="#/Messages" onclick="SetActiveAccountHeading(this);" ...

Should we fulfill the CSV Stringify promise in a test, or should we terminate the test when a function is invoked?

Currently, I'm attempting to simulate CSV Stringify using AngularJS, with the intention of extracting two parameters for future verification. My plan is to verify if certain options were correctly implemented later in the test. it("converts latitude ...