我有一个如下所示的 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;
}
});
我在我的应用程序主页上的 Controller 上使用此服务,如下所示:
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
):
div(class='container')
h1 Welcome {{user}}
// other stuff
此页面的 Controller 如下所示:
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。有一个 $cookies service在 Angular 。
对于本地存储解决方案,您必须四处搜索。
将用户对象推送到一个永不过期的 cookie 中,然后在下次他们重新加载页面时发出请求之前尝试从那里读取它。
关于javascript - 如何通过页面刷新让Angular服务中的数据持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28955560/