I have an angular Service:
presence.service('AuthService', function($http, PresenceURLService){
var apiURL = PresenceURLService.apiURL;
this.isLogged = false,
this.access_token = "",
this.login = function(credentials, callback){
var configura = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
};
$http({
method:'POST',
url: apiURL+'login',
data: credentials,
config: configura
}).then(function(response){
//success
this.isLogged = response.data.response;
this.access_token = response.data.access_token;
callback(response.data);
}, function(response){
//error
callback(response.data);
});
}
});
Whenever an user tries to login, the API returns tru or false and it is stored in this.isLogged
. Works fine.
I have this code on run for the app, in order to stop the state load if the user is not logged:
presence.run(function($rootScope, $location, $state, AuthService) {
$rootScope.$on( '$stateChangeStart', function(e, toState , toParams, fromState, fromParams) {
var isLogin = toState.name === "login";
if(isLogin){
return; // no need to redirect
}
console.log("State we are going to: "+toState.name);
// now, redirect only not authenticated
var logged = AuthService.isLogged;
console.log("Before load must check the AuthService isLogged var: "+logged);
if(logged === false) {
e.preventDefault(); // stop current execution
$state.go('login'); // go to login
}
});
});
In this code logged is always false. But, previously, when I call login() function, it is stored true.
Why it losses the data and how to obtain this behaviour?