1

I am storing authentication token in $rootScope . This token will be sent as part of header in every request via interceptor.

<code>
 $rootScope.jwtToken=successfulResponse.data.body;
</code>

Interceptor code is as below :-

var bpInterceptor = function($q,$rootScope){
return {
    request : function(config){

        if($rootScope.jwtToken !== undefined){
            config.headers.Authorization = $rootScope.jwtToken.token;  
        }
        return config;
    }
}
};
</code>

Q) Does $rootScope have different object for two browser sessions?

2
  • of course. normally you read token from cookies and attach to it. Commented May 24, 2016 at 14:18
  • 100% yes, store it on a persistent cookie or localstorage then fetch it to rootscope on new browser sessions. Commented May 24, 2016 at 14:19

1 Answer 1

1

Angular code is executed client side only, so any state will disappear once you reload the page.

If you want to keep information between two user session, you have many options:

  • Keep that info in the URL using $location or location
  • Store that info in localStorage and retrieve it next time
  • Persist the information server side and query your server to get it back

Follow-up:

Once you get your token you can do:

localStorage.setItem('myToken', $rootScope.jwtToken);

And when you load your application, check if a token has been stored:

$rootScope.jwtToken = localStorage.getItem('myToken');
Sign up to request clarification or add additional context in comments.

2 Comments

Could you also provide an example of how to use localStorage. I tried $window.sessionStorage.jwtToken , but it did not seem to work as the set value was not accessible on another controller. Currently I am setting the value in $rootScope and its accessible across the other controller. However on page refresh the token is lost and redirected to login page. Please advise.
@user3504187 I've added an example of how to use localStorage. Otherwise you can find that anywhere online: it is not related to Angular.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.