javascript angularjs $state 和 $rootScope.$on($stateChangeStart) 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32680292/
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 15:37:07  来源:igfitidea点击:

angularjs $state and $rootScope.$on($stateChangeStart) issue

javascriptangularjsangular-ui-routerstate

提问by user3581552

I've went through multiple questions but haven't find a solution.

我已经解决了多个问题,但还没有找到解决方案。

I have an issue with states handling.

我对状态处理有疑问。

$urlRouterProvider.otherwise( function($injector, $location) {
    var $state = $injector.get("$state");
    $state.go("cover");
});

$stateProvider
    .state('auth', {
        url: '/auth',
        templateUrl: '../views/authView.html',
        controller: 'AuthController as auth'
    })
    .state('users', {
        url: '/users',
        templateUrl: '../views/userView.html',
        controller: 'UserController as user'
    })
....

this how routing works in my app.

这就是路由在我的应用程序中的工作方式。

app.run(function($rootScope, $state, $location) {
    $rootScope.$on('$stateChangeStart', function(event, toState, fromState) {

        //ERROR IS IN THIS BLOCK
        if($rootScope.authenticated && $rootScope.onboard == 0) {

            //event.preventDefault();

            $state.transitionTo("onboard", null, {notify:false});
            $state.go('onboard');
        }
...

Everytime I change my route, that block fires hundred times, but I want it simply check whether user is authenticated and completed some forms or no and if no just redirect to the forms itself.

每次我更改路线时,该块都会触发数百次,但我希望它只是检查用户是否已通过身份验证并完成某些表单或没有,如果没有则重定向到表单本身。

I've tried different ways with preventDefault(); or without, same issue.

我尝试了不同的方法preventDefault();或者没有,同样的问题。

回答by Radim K?hler

Firstly, we should always try to check, if user is not already going (being redirected previously)to the state 'onboard'. If yes, stop any other handling ( simply return).

首先,我们应该始终尝试检查用户是否还没有(之前被重定向)到 state 'onboard'。如果是,停止任何其他处理(简单return)。

$rootScope.$on('$stateChangeStart', function(event, toState, fromState) {

    // in case, that TO state is the one we want to redirect
    // get out of here   
    if(toState.name === "onboard"){
       return;
    }

    if($rootScope.authenticated && $rootScope.onboard == 0) {

        // this should not be commented
        //event.preventDefault();
        // because here we must stop current flow.. .
        event.preventDefault();

        $state.transitionTo("onboard", null, {notify:false});
        $state.go('onboard');
    }
 ...

Check the angularjs ui-router generates infinite loop

检查angularjs ui-router 生成无限循环