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?
The easiest way to reload the current page without losing form data, use WebStorage where you have -persistent storage (localStorage) or session-based (sessionStorage) which remains in memory until your web browser is closed. window. onload = function() { var name = localStorage.
Syncfusion Angular UI Components has support for persisting component's state across page refreshes or navigation. To enable this feature, set enablePersistence property as true to the required component. This will store the component's state in the browser's localStorage object on page unload event.
From then on, the Angular framework kick in and loads the appropriate modules and pages as route changes. When you refresh the page you lose all the state of the application since you are reloading the index. html with all the required dependencies again.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With