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

use*_*552 6 javascript state angularjs angular-ui-router

我经历了多个问题,但没有找到解决方案.

我有处理状态的问题.

$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'
    })
....
Run Code Online (Sandbox Code Playgroud)

这个路由在我的应用中如何工作.

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');
        }
...
Run Code Online (Sandbox Code Playgroud)

每当我改变我的路线时,该块会触发数百次,但我希望它只是检查用户是否经过身份验证并完成了某些表格,或者是否只是重定向到表单本身.

我尝试过不同的方式preventDefault(); 或没有,同样的问题.

Rad*_*ler 6

首先,我们应该总是尝试检查,如果用户尚未进入(先前被重定向)状态'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');
    }
 ...
Run Code Online (Sandbox Code Playgroud)

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