How to make data in Angular service saved through page refresh

I have an Angular service that looks like this:

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 the controller on the main page of my application, for example:

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

In the users state, the following is displayed (I am using ui-router to connect it to ui-view ):

 div(class='container') h1 Welcome {{user}} // other stuff 

The controller for this page is as follows:

 lunchrControllers.controller('UserController', ['$scope', '$http', '$state', 'authService', function ($scope, $http, $state, authService) { $scope.user = authService.currentUser(); //other stuff }]); 

When a user is sent to this page by calling $state.go('users') , {{user}} is populated correctly.

The problem, however, is that refreshing the page now results in an empty {{user}} error. How can I save the data stored in the service on the update page?

+5
source share
1 answer

You can set a cookie or use localStorage. There is a $ cookie in angular.

To solve localstorage you have to search google.

drag the user object into a cookie that never expires, and then try reading it from there before making your request the next time it reloads the page.

+6
source

Source: https://habr.com/ru/post/1215023/


All Articles