1

I am trying to create a session redirect if the user is not logged in. The code is working as I expected. However, when I take a look on the console, An error occurs (as in indicated in the title). I can not seem to fix this and I need some help.

var domainName = window.location.href;
var domainName = domainName.split("/");
var domainName = domainName[0] + "//" + domainName[2];

var app = angular.module("app", []);

app.run(run);

run.$inject = ["$window", "$rootScope", "$cookies"];

function run($window, $rootScope, $cookies){

    // Runs everytime the URL changes
    $rootScope.$on('$locationChangeStart', function(event, current, previous) {
        // If the user is not logged-in and is not trying to access the register or log-in, It will go back to the log-in page
        // if(!$cookies.get('user') && current != domainName+"/#/"){
        if(current != domainName+"/#/"){
            $window.location.href = domainName+"/#/";
        //  Create a scope that will remind the users regarding the session
        //  $rootScope.sessionError = "Please Enter Exam Code before taking the exam";
        }
    });
}
Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116

1 Answers1

1

As the error message describes, you are facing an infinite loop.
When the event $locationChangeStart is fired you check the url and redirect to another page. When you redirect the url is changed again, firing the $locationChangeStart again and so on.
You need to find another way to validate if the user is logged or not.

I don't know if it's going to work, but try checking if current is different from previous.

$rootScope.$on('$locationChangeStart', function(event, current, previous) {
    if(current !== previous && current != domainName+"/#/"){
        $window.location.href = domainName+"/#/";
    }
});

I suggest you to use $location for changing the URL.
Docs
Related post

Community
  • 1
  • 1
Gabriel Hobold
  • 693
  • 6
  • 16
  • the condition does not trigger anymore, may I know why you suggested $location over $window? – Dean Christian Armada Jun 05 '16 at 06:34
  • I think it's the angular way of doing such thing and `$location` provides some useful methods. The `$window` is just a reference to window object, but off course, you can keep using `$window` wihtout any problem. I think it's more like a convention. – Gabriel Hobold Jun 05 '16 at 06:44
  • You're welcome ;) About your question, I can't think in a solution to resolve the loop problem without removing the redirect from the event. Because every time the url changes will trigger the event again and again. I think you need rethink the way you're doing this or create a validation to not enter in a infinite loop. – Gabriel Hobold Jun 05 '16 at 06:56
  • Yes, probably will try a different approach! (y) – Dean Christian Armada Jun 05 '16 at 06:58
  • I finally solved it! I used $location insted of $window and it worked like a charm! – Dean Christian Armada Jun 05 '16 at 13:49