Renaud is Not Bill Gates
Renaud is Not Bill Gates

Reputation: 2084

maintaining session from server application in angularjs

I have an angularjs application, in this application I have a login form when I submit it I call a rest service to authenticate the user to my server application, as following :

$http.get('http://localhost:8080/user', {
                headers : credentials ? {
            authorization : "Basic "
            + btoa(credentials.username + ":"
              + credentials.password)
          } : {};
              }).then(function(response) {
                if (response.data.name) {
                  $rootScope.authenticated = true;
                  $rootScope.username=response.data.name;
                  $rootScope.roles=response.data.authorities;
                  $rootScope.sessionid=response.data.details.sessionId;
                } else {
                  $rootScope.authenticated = false;
                }
              }, function() {
                $rootScope.authenticated = false;
              });

So the $rootScope will have all the informations about the authenticated user, but when I refresh my application, all those informations I attached to $rootScope are removed.

Notice that http://localhost:8080/user will always maintain the session.

How can I solve that ?

Upvotes: 0

Views: 538

Answers (2)

Yassine Badache
Yassine Badache

Reputation: 1851

Check for Local and Session storage service. You can easily attach informations to variables with getters and setters, and retrieving them through page refreshing.

Example: You can set a variable like this: localStorageService.set('myVar', data);

And then retrieve it in another controller, after refreshing, or elsewhere in your application with: localStorageService.get('myVar');

It is rather well documented and easy to use.

Upvotes: 1

Walfrat
Walfrat

Reputation: 5353

You can either store it in sessionStorage or just get the current user logged from server side. Then in order to retrieve them use an angular.run

angular.run(...function($http, $rootScope){
     // either use session storage or $http to retrieve your data and store them in $rootScope.
    // if you use $http i suggest you to store the promise of $http to be sure in your controller/route to wait that it has been resolved.
 });

The fact that you're loosing what you store when using f5 is normal, you lose all javascript context when doing so. The usage of angular.run permit to use the request before any controller is called However with $http you may need to wait the end of the promise. So it's better to have a reference to the promise store in $rootScope to be able to use it in the javascript part. You can reference directly the data in the templates as they will get refresh as soon they will be loaded.

Upvotes: 1

Related Questions