如何通过页面刷新持久化Angular服务中的数据 [英] How to make data in Angular service persist through page refresh
问题描述
我有一个类似Angular的服务:
I have an Angular service that looks like:
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 = "";
})
}
}]);
在 users
状态下显示以下内容(我正在使用 ui-router
将其插入 ui-view
中):
With the users
state displaying the following (I'm using ui-router
to plug this in a ui-view
):
div(class='container')
h1 Welcome {{user}}
// other stuff
此页面的控制器如下:
lunchrControllers.controller('UserController', ['$scope', '$http', '$state', 'authService',
function ($scope, $http, $state, authService) {
$scope.user = authService.currentUser();
//other stuff
}]);
当用户通过 $ state.go('users')
调用进入此页面时,将正确填充 {{user}}
.
When the user taken to this page through the $state.go('users')
call, {{user}}
is correctly populated.
但是,问题在于,现在刷新页面会导致 {{user}}
为空.如何通过页面刷新持久化存储在服务中的数据?
The problem, however, is that refreshing the page now results in {{user}}
being empty. How can I have the data stored in the service persist through page refreshes?
推荐答案
您可以设置cookie或使用localStorage.角度中有一个 $ cookies服务.
You can set a cookie or use localStorage. There is a $cookies service in angular.
对于本地存储解决方案,您必须四处搜寻.
For a localstorage solution you will have to google around.
将用户对象放入永不过期的cookie中,然后尝试从那里读取它,然后在下次重新加载页面时发出请求.
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.
这篇关于如何通过页面刷新持久化Angular服务中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!