1

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

Nick
  • 19
  • 3
  • What do you mean by *but it calls Login controller anyway. How can I disable it? Do not fire Login controller in this case?* – Pankaj Parkar Aug 18 '17 at 19:05
  • @PankajParkar I mean If user is logged in I need to redirect to `/home`, and I don't need run `Login` controller. Inside `Login` controller I call API. I checked - app redirects to `/home` and calls that API at the same time. Sorry for my English. – Nick Aug 18 '17 at 19:09
  • Also I added `console.log('this is login controller')` inside `Login` controller. App redirects me to `/home` and I can see `this is login controller` in my console. – Nick Aug 18 '17 at 19:14
  • Why don't you use that factory in your controller ? Since resolve part of the route is to provide data for controller so controller calls after resolve – Mumin Korcan Aug 18 '17 at 19:29
  • @Nick you could think of shift your implementation in [this way](https://stackoverflow.com/a/16346403/2435473) with resolve way you can't cancel your current navigation – Pankaj Parkar Aug 18 '17 at 19:31
  • @PankajParkar, got it. Thanks – Nick Aug 18 '17 at 19:34
  • @PankajParkar is it possible to use promise inside `$locationChangeStart`? `if (loggin === 1)` was example, I call API `$http('/api/islogin'...)...` – Nick Aug 18 '17 at 20:05

1 Answers1

0

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.

Nick
  • 19
  • 3