在我的角度控制器中,当从作为字符串返回的 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>