Programador Adagal Programador Adagal - 1 month ago 11
AngularJS Question

Angular Service dont stores boolean

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?

Answer

This is because context in which you set isLogged is not AuthService. Read more here how this works

Try this instead:

presence.service('AuthService', function($http, PresenceURLService){
    var that = this; // In order to access correct context within callback
    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
            // Use that instead of this here. As this doesn't refers to AuthService
            that.isLogged = response.data.response;
            that.access_token = response.data.access_token;
            callback(response.data);
        }, function(response){
            //error
            callback(response.data);
        });
    }
});