The way I actually do it is to load it automatically at the beginning of factory
and then just make the request where I need it. The only difference is that I use localStorage
instead of sessionStorage
, but this is easily at your discretion.
Example:
var minhaToken;
function setToken() {
minhaToken = localStorageService.get('tokenName'); //tokenName é um exemplo do nome da 'data' aramazenada na storage
};
function getToken () {
return minhaToken;
};
return {
setToken: setToken(),
getToken: getToken
};
And when it is necessary to get the token, let's say inside a controller, you just have to make the request:
$scope.token = usuarioAPI.getToken();
This way you can store it inside your service and request it whenever you need it.
Important note:
I've used localStorageService.get
since it's the plugin (third-party - not native to AngularJS) that I use. You can choose from the most diverse options you will use, whether it is a third-party plugin or AngularJS
itself, see this link . I particularly prefer to use this here because it has more freedom and more options than AngularJS
.
Edited:
To send the parameters to your requests, you need to merge them with the ones you already have - I assume it's config.baseUrl
if not, you can create a variable inside factory
and then move to $http
. See:
var configHeader;
function setToken() {
minhaToken = localStorageService.get('tokenName'); //tokenName é um exemplo do nome da 'data' aramazenada na storage
if(minhaToken){
configHeader = {headers: {
'token': minhaToken,
//e/ou outros valores
}
} else {
//Outra lógica caso o usuario ainda não tenha autenticado.
};
};
return $http.post(config.baseURL + '/SecurityVraptor/usuario/', usuario, configHeader );
return $http.get(config.baseURL + '/SecurityVraptor/usuario/listarTodos', configHeader );
Note: Some time ago I stopped using this way for some internal changes in the work and started to use directly in url
, but it is completely at your discretion. I may also be missing out on syntax, as I have not been able to get into this for a long time, but I think you can get the idea already.
In the references of AngularJS
in the area of $http
has the information of the order of the objects, see: link $ http