Different values stored storing a string with localStorage and $localStorage with Angular 1.

1k views Asked by At

In my angular controller, I am trying to save a token when returned from an API end point which is returned as a string. For this example, I've replaced it with the variable testData.

var testData = "testdata"

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

For the first line, this is what is stored:

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

First the second line:

{"jwtToken" : "testdata"}

I understand why the key is changing but what I don't understand is why there is a double "" around the data string stored in the value of the key by the first line.

Has anyone come across this before? Am I doing anything wrong?

Best efforts to add the code below.

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;
      // Try 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>

1

There are 1 answers

1
epascarello On

Why the double quotes

I would need to look at the source code, but most likely the reason why they put quotes around the string is so they can use JSON.parse() so and get the correct object/array/string out of the storage without having to try to figure out the types.

Basic idea:

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

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

Why do they prepend the key name?

They can loop over the keys and know what localstorage keys are angulars and what ones are something else. They they can populate their object.

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