最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular ui router - Redirection doesn't work at all - Stack Overflow

programmeradmin1浏览0评论

I'm using ui.router for routing in my Angular app. There is a typical login scenario, where I'm redirecting a user to the login url if he's not logged in. Without the ui.router library, this worked fine using $routeChangeStart event bined with $location.path. Now, I'm using the $stateChangeStart event, bined with $state.go, and the nothing works! It also sends my browser into an infinite loop. I read from other sources that this is a known bug, and none of the suggested solutions work for me. Moreover, $location.path too doesn't redirect to the login page.

This is how I've configured my paths:

 .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('main', {
            url: '/',
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
        .state('about', {
            url: '/about',
            templateUrl: 'views/about.html',
            controller: 'AboutCtrl'
        })
        .state('login', {
            url: '/login',
            templateUrl: 'views/loginform.html',
            controller: 'LoginCtrl'
        });
    $urlRouterProvider.otherwise("/");
}])

And my run method:

.run(['$state', '$rootScope', '$location', function($state, $rootScope, $location) {
    //Check when routing starts
    //event, next, current
    $rootScope.$on( '$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
        //Redirect to login if the user is not logged in
        if (!isUserLoggedIn) {

            //Some suggestion
            //e.preventDefault();
            console.log('Not logged in');

            //Infinite loop, kills my browser!
            $state.go('login');
            $state.transitionTo('login');

            //Some suggestion
            $state.go('login', { url: '/login'});

            //Doesn't work
            $location.path('/login');

            //$location.path( $state.href('login');
            console.log('Redirected');
        }
    });

I'm using ui.router for routing in my Angular app. There is a typical login scenario, where I'm redirecting a user to the login url if he's not logged in. Without the ui.router library, this worked fine using $routeChangeStart event bined with $location.path. Now, I'm using the $stateChangeStart event, bined with $state.go, and the nothing works! It also sends my browser into an infinite loop. I read from other sources that this is a known bug, and none of the suggested solutions work for me. Moreover, $location.path too doesn't redirect to the login page.

This is how I've configured my paths:

 .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('main', {
            url: '/',
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
        .state('about', {
            url: '/about',
            templateUrl: 'views/about.html',
            controller: 'AboutCtrl'
        })
        .state('login', {
            url: '/login',
            templateUrl: 'views/loginform.html',
            controller: 'LoginCtrl'
        });
    $urlRouterProvider.otherwise("/");
}])

And my run method:

.run(['$state', '$rootScope', '$location', function($state, $rootScope, $location) {
    //Check when routing starts
    //event, next, current
    $rootScope.$on( '$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
        //Redirect to login if the user is not logged in
        if (!isUserLoggedIn) {

            //Some suggestion
            //e.preventDefault();
            console.log('Not logged in');

            //Infinite loop, kills my browser!
            $state.go('login');
            $state.transitionTo('login');

            //Some suggestion
            $state.go('login', { url: '/login'});

            //Doesn't work
            $location.path('/login');

            //$location.path( $state.href('login');
            console.log('Redirected');
        }
    });
Share Improve this question edited Jun 22, 2017 at 16:47 laser 1,37613 silver badges14 bronze badges asked Oct 1, 2014 at 6:30 Rutwick GangurdeRutwick Gangurde 4,91211 gold badges55 silver badges89 bronze badges 2
  • 1 Where is isUserLoggedIn defined? – Phil Commented Oct 1, 2014 at 6:36
  • I have an Authentication service, I skipped it from this code due to some official reasons. It worked well with the default routing. – Rutwick Gangurde Commented Oct 1, 2014 at 6:38
Add a ment  | 

2 Answers 2

Reset to default 9

What we would need here, is to do NOT redirect, if the state TO is already the 'login'.

Just a drafted adjustment would be

$rootScope.$on( '$stateChangeStart', function(e, toState  , toParams
                                               , fromState, fromParams) {

    var isLogin = toState.name === "login";

    if(isLogin){

       return; // no need to redirect anymore 
    }
    ...

And also, we should call $state.go('login'); with the event.preventDefault();

 ...
 // also prevent default on redirect
 $state.go('login');
 event.preventDefault(); 
 ...

Please check this Q & A How can I fix 'Maximum call stack size exceeded' AngularJS And a plunker with similiar solution

I used something similar to this:

MyApp.run(['$rootScope', '$state', function ($rootScope, $state) {
  // The event
  $rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
    // Is user already logged in?
    var isUserLoggedIn = $rootScope.isUserLoggedIn();

    if (isUserLoggedIn) {
      // don't let user visit login state, he's already logged in.
      $state.go('home');
      // preventDefault as described in @radim's answer
      e.preventDefault();
    } else if (toState.name === "login") {
      // user is not logged in and is not going to login state right now, send him there first.
      $state.go('login');
      // preventDefault as described in @radim's answer
      e.preventDefault();
    }
  });
}]);
发布评论

评论列表(0)

  1. 暂无评论