[英]How to make data in Angular service persist through page refresh
I have an Angular service that looks like: 我有一个Angular服务,看起来像:
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;
}
});
I use this service on a controller on the main page of my application like so: 我在我的应用程序主页上的控制器上使用此服务,如下所示:
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 = "";
})
}
}]);
With the users
state displaying the following (I'm using ui-router
to plug this in a ui-view
): users
状态显示以下内容(我使用ui-router
在ui-view
插入):
div(class='container')
h1 Welcome {{user}}
// other stuff
The controller for this page looks like: 此页面的控制器如下所示:
lunchrControllers.controller('UserController', ['$scope', '$http', '$state', 'authService',
function ($scope, $http, $state, authService) {
$scope.user = authService.currentUser();
//other stuff
}]);
When the user taken to this page through the $state.go('users')
call, {{user}}
is correctly populated. 当用户通过$state.go('users')
调用访问此页面时, {{user}}
被正确填充。
The problem, however, is that refreshing the page now results in {{user}}
being empty. 但问题是,现在刷新页面会导致{{user}}
为空。 How can I have the data stored in the service persist through page refreshes? 如何通过页面刷新保持服务中存储的数据?
You can set a cookie or use localStorage. 您可以设置cookie或使用localStorage。 There is a $cookies service in angular. 有角度的$ cookies服务 。
For a localstorage solution you will have to google around. 对于本地存储解决方案,您将不得不谷歌。
shove the user object into a cookie that never expires and then try to read it from there before making your request next time they reload the page. 将用户对象推送到永不过期的cookie,然后尝试从那里读取它,然后在下次重新加载页面时发出请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.