在第一个ui-router请求期间,解析映射是否应重定向到“其他”位置?

时间:2014-05-13 21:16:03

标签: angularjs angular-ui-router

我发现解析图非常有用。如果我在页面中请求状态更改,如果任何结果失败,状态将不会按预期结束/成功。

我似乎没有在我的应用中执行会影响此行为的任何内容,但我注意到如果我尝试直接在我的应用中加载状态(通过网址,例如 app.com/my/状态)并且结算失败,没有状态可以回退,看到这是请求的第一条路线。

我原本以为它会落后于我的'否则'位置,定义为' /'。这是预期的功能吗?如果没有,是否有一种有效的方法来解决这个问题?

我目前的解决方案涉及捕获状态错误并设置位置,如果没有fromState(意味着错误发生在第一个状态)

EbApp.run([
    '$rootScope', '$location', '$timeout',
    function($rootScope, $location, $timeout)
    {
        var first_state_error = $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState)
        {
            // Redirect to the app root on a state error during the first state request
            if ( ! fromState.name) {
                $timeout(function()
                {
                    $rootScope.$apply(function()
                    {
                        $location.path('/').search({});
                    });
                });
            }
            // Remove watching state change errors once there is a fromState available
            else {
                first_state_error();
            }
        });
    }
]);

1 个答案:

答案 0 :(得分:1)

如果你的州解决职能失败,你就不要去"否则"路由,因为stateManager找到路径去。 你需要测试的是toState名称(不是fromState),如果你想要有不同的错误路由,可以这样:

        $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
            if (toState.name === 'yourRouteName') {
                return $state.go('whereverRoute');
            }
            return error;
        });

或只是

        $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
            $location.path('/')
        });

如果您想要始终重定向到您的根