Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  13] [ 2]  / answers: 1 / hits: 16062  / 9 Years ago, tue, march 10, 2015, 12:00:00

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 = ;
})
}
}]);


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


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.



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?


More From » angularjs

 Answers
35

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.



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.


[#67506] Saturday, March 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breap

Total Points: 606
Total Questions: 96
Total Answers: 108

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
breap questions
Thu, Jun 24, 21, 00:00, 3 Years ago
Wed, Mar 18, 20, 00:00, 4 Years ago
Mon, Oct 7, 19, 00:00, 5 Years ago
;