Modifying value of my IsAuthenticated in AngularJS

2

When the token is different from null, my IsAuthenticated must be positive,

app.controller("HomeCtrl", function ($scope, $location) {
    let token = localStorage.getItem("token");
    $scope.user = JSON.parse(token);

    if (token === null) {
        $scope.IsAuthenticated = false;
        $('body').removeClass('nav-md');
        $('body').addClass('login');
        $location.path('/login');
        console.log($scope.IsAuthenticated);
    } else{
        $scope.IsAuthenticated = true;
        $('body').removeClass('login');
        $('body').addClass('nav-md');
        $location.path('/');
        console.log($scope.IsAuthenticated);
    }

    $scope.doLogout = function () {
        localStorage.removeItem('token');
        $scope.IsAuthenticated = false;
        $location.path('/login');
        console.log("chamou aqui");
        location.reload();
    }
});

Even when the user logs my IsAuthenticated value is false. How do I solve the problem? Below is my LoginCtrl code

app.controller("LoginCtrl", function ($scope, LoginAPI, $location) {

    $scope.doLogin = function (model) {
        if (model.username === undefined || model.password === undefined) {
            return false;
        }

        LoginAPI.post(model).success(function (results) {
            localStorage.removeItem('token');
            //Armazena o token no localStorage
            localStorage.setItem('token', JSON.stringify(results));
            //preciso que o meu IsAuthenticated fique true antes de executar o comando abaixo
            $location.path('/');
        })
         .error(function (Error) {
             console.log(Error);
         }
    };
});
    
asked by anonymous 14.03.2017 / 18:33

2 answers

2

Instead of $location.path('/'); just place window.location.href = '/home/index'; Because as you will be logging in, the first moment the page should be updated and reloaded. By doing this the problem will be solved.

    
17.03.2017 / 12:44
2

This happens because you are assigning value to the LoginCtrl, the value has to be passed by HomeCtrl, which is what I understood and its main scope

    
14.03.2017 / 18:46