user3504187 user3504187 - 6 months ago 27
AngularJS Question

$rootScope behaviour in angularJs

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?

Answer

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');