Ramiro Garcilazo Ramiro Garcilazo - 5 months ago 24
AngularJS Question

Check login status in routeProvider

I'm working on an Angular project but I'm having a little problem and I'd appreciate any help because I'm really lost. Basically I need to check if a user is logged in, and if he is, he should not be allowed to access a certain view/route, here's the code I'm using for this:

'use strict';

angular.module('testApp')
.config(function ($routeProvider) {
$routeProvider
.when('/registroVisitante', {
template: '<registro-visitante></registro-visitante>',
resolve: {
"check": function(Auth, $location) {
console.log(Auth.isLoggedIn());
if (!Auth.isLoggedIn()) {
alert("Access allowed");
} else {
$location.path('/'); //redirect user to home.
alert("Access denied");
}
}
}
});
});


The problem itself is that, this is actually working, but only when I try to access the route via an anchor click or ng-click or whatever, however, when I type the route in the address bar it lets me access but it shouldn't, anyone has any idea why?

Answer

Try this

angular.module('testApp')
    .config(function ($routeProvider) {
        $routeProvider
            .when('/registroVisitante', {
                template: '<registro-visitante></registro-visitante>',
                resolve: {
                    "check": function (Auth, $location) {
                        Auth.isLoggedIn(function (response) {
                            console.log(response);
                            if (response) {
                                $location.path('/'); //redirect user to home.
                            }
                        });
                    }
                }
            });
    });

The problem was that it was an asynchronous request and maybe when it got to the if it was undefined.