javascript Angular ui 路由器 - 重定向根本不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26135382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:32:48  来源:igfitidea点击:

Angular ui router - Redirection doesn't work at all

javascriptangularjsangular-ui-routerurl-routing

提问by Rutwick Gangurde

I'm using ui.routerfor 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 combined with $location.path. Now, I'm using the $stateChangeStartevent, combined 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.pathtoo doesn't redirect to the login page.

ui.router在我的 Angular 应用程序中用于路由。有一个典型的登录场景,如果他没有登录,我会将用户重定向到登录 URL。如果没有 ui.router 库,这可以很好地使用 $routeChangeStart 事件与$location.path. 现在,我将$stateChangeStart事件与 结合使用$state.go,但没有任何效果!它还使我的浏览器进入无限循环。我从其他来源读到这是一个已知的错误,并且没有一个建议的解决方案适合我。此外,$location.path也不会重定向到登录页面。

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 runmethod:

而我的run方法:

.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');
        }
    });

回答by Radim K?hler

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

我们在这里需要的是不要重定向,如果状态 TO 已经是“登录”。

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();

而且,我们应该打电话$state.go('login');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' AngularJSAnd a plunkerwith similiar solution

请检查此问答如何修复“超出最大调用堆栈大小”AngularJS和具有类似解决方案的 plunker

回答by GabLeRoux

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();
    }
  });
}]);