我有一个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;
}
});
我在我的应用程序主页面上的控制器上使用此服务,如下所示:
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
此页面的控制器如下所示:
lunchrControllers.controller('UserController', ['$scope', '$http', '$state', 'authService',
function ($scope, $http, $state, authService) {
$scope.user = authService.currentUser();
//other stuff
}]);
当用户通过$state.go('users')
来电转到此页面时,{{user}}
已正确填充。
但问题是,现在刷新页面会导致{{user}}
为空。如何通过页面刷新保持服务中存储的数据?
答案 0 :(得分:7)
您可以设置Cookie或使用localStorage。角度为$cookies service。
对于本地存储解决方案,您将不得不谷歌。
将用户对象推送到永不过期的cookie中,然后尝试从那里读取它,然后在下次重新加载页面时发出请求。