存储带有localStorage的字符串的不同值和带有Angular 1的$ localStorage。

时间:2017-01-06 20:51:47

标签: javascript angularjs ng-storage

在我的角度控制器中,我试图在从作为字符串返回的API端点返回时保存令牌。对于这个例子,我用变量testData替换它。

var testData = "testdata"

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

对于第一行,这是存储的内容:

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

首先是第二行:

{"jwtToken" : "testdata"}

我理解为什么密钥正在改变,但我不明白为什么在第一行存储在密钥值中的数据字符串周围有一个双“”。

有没有人遇到过这个?我做错了吗?

尽最大努力添加以下代码。

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 个答案:

答案 0 :(得分:1)

为什么双引号

我需要查看源代码,但很可能是他们在字符串周围放置引号的原因是他们可以使用JSON.parse(),并从存储中获取正确的对象/数组/字符串不得不试图找出类型。

基本理念:

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

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

为什么它们会在键名前加上?

他们可以遍历键,知道哪些localstorage键是angulars,哪些是其他东西。他们可以填充他们的对象。

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