Javascript 如何通过页面刷新使Angular service中的数据持久化
我有一个角度服务,看起来像:Javascript 如何通过页面刷新使Angular service中的数据持久化,javascript,angularjs,Javascript,Angularjs,我有一个角度服务,看起来像: var lunchrServices = angular.module('lunchrServices', []); lunchrServices.service('authService', function () { var user = null; this.login = function (userEmail) { user = userEmail; }; this.logout = function (
var lunchrServices = angular.module('lunchrServices', []);
lunchrServices.service('authService', function () {
var user = null;
this.login = function (userEmail) {
user = userEmail;
};
this.logout = function () {
user = null;
};
this.currentUser = function(){
return user;
}
});
lunchrControllers.controller('UserController', ['$scope', '$http', '$state', 'authService',
function ($scope, $http, $state, authService) {
$scope.user = authService.currentUser();
//other stuff
}]);
我在应用程序主页上的控制器上使用此服务,如下所示:
var lunchrControllers = angular.module('lunchrControllers', []);
lunchrControllers.controller('MainPageController', ['$scope', '$http', '$state', 'authService',
function ($scope, $http, $state, authService) {
$scope.logIn = function () {
$http.post('/api/users/authenticate', {email: $scope.email, password: $scope.password}).
success(function (data, status, headers, config) {
// lines of interest
authService.login($scope.email);
$state.go('users');
}).
error(function (data, status, headers, config) {
$scope.errorMessages = data;
$scope.password = "";
})
}
}]);
当用户
状态显示以下内容时(我正在使用ui路由器
将其插入ui视图
):
此页的控制器如下所示:
var lunchrServices = angular.module('lunchrServices', []);
lunchrServices.service('authService', function () {
var user = null;
this.login = function (userEmail) {
user = userEmail;
};
this.logout = function () {
user = null;
};
this.currentUser = function(){
return user;
}
});
lunchrControllers.controller('UserController', ['$scope', '$http', '$state', 'authService',
function ($scope, $http, $state, authService) {
$scope.user = authService.currentUser();
//other stuff
}]);
当用户通过$state.go('users')
调用进入此页面时,{{user}}
已正确填充
然而,问题是刷新页面现在会导致
{{user}}
为空。如何通过页面刷新保持服务中存储的数据?您可以设置cookie或使用localStorage。有一个角度
对于localstorage解决方案,您必须在google上四处搜索
将用户对象放入一个永不过期的cookie中,然后在下次用户重新加载页面时提出请求之前尝试从中读取该对象。祝贺您的20k帖子。谢谢!现在我没有别的东西要解锁了,所以我要睡觉了:)本地存储解决方案: