$routeProvider – not load controller after failed resolve

Issue

I’d like to check something in router. In some condition I should redirect on anothter page.

I set up router:

when('/login', {
 templateUrl: 'login.html',
 controller: 'Login',
 resolve : {
   'checkLogin': ['checkLogin', function(checkLogin){
      return checkLogin.isLogin();
    }]
 }
})

And factory:

app.factory('checkLogin', [function() {
    "use strict";
    return {
        isLogin: function() {
            if (loggin === 1) {
               $location.path('/home');
            };
        }
    };
}]);

And If loggin === 1 it redirects to /home, but it calls Login controller anyway. How can I disable it? Do not fire Login controller in this case?

Thanks

Solution

I decided to use $locationChangeStart advised by @PankajParkar.

app.run(['$rootScope', '$location', function($rootScope, $location) {
    "use strict";
    $rootScope.$on('$locationChangeStart', function(event, next, current) {
        if (next.indexOf('login') !== -1) {
            if (loggin === 1) {
                event.preventDefault();
                $location.path('/home');
            }
        }
    });
}]);

Not sure it looks good.

Answered By – Nick

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.