错误时返回上一个状态

时间:2015-03-04 19:39:06

标签: angularjs angular-ui-router

我在我的应用程序中使用角度ui-router,并且每当发生错误时,例如HTTP 404HTTP 500等,我希望显示一个错误页面,其中包含错误的详细信息和一个按钮,以便用户返回之前的状态或页面。

我正在使用HTTP响应拦截器来监视HTTP错误,然后执行$state.go('error')以显示错误页面。

我也在所有错误承诺函数中执行$state.go('error')

我的控制器中有以下代码,用于创建一个还原点,当用户点击“返回”时,该点将重新加载控制器。链接在错误页面上。

// create a restore point for the error page to return to.
$rootScope.previousState = $state.current.name;
$rootScope.previousStateParams = $state.current.params;

这是我的error.html页面:

<div class="alert alert-danger alert-dismissible" role="alert">
    <div class="medium">{{errorMessage}}</div>
    <br />
    <div>{{reason}}</div>
    <br />
    <div>
        <a href="#" data-ng-click="return()">Go back</a>
    </div>
</div>

我的error state配置:

$stateProvider.state('error', {
    templateUrl: paths.templates + 'error.html',
    params: ['errorMessage', 'reason'],
    controller: function ($rootScope, $scope, $state, $stateParams) {
        $scope.errorMessage = $stateParams.errorMessage;
        $scope.reason = $stateParams.reason;
        $scope.return = function ()
        {
            console.log($rootScope.previousStateParams);
            $state.transitionTo($rootScope.previousState, $rootScope.previousStateParams, {
                reload: true,
                inherit: false,
                notify: true
            });
        };
    },
    data: {
        access: [roles.all]
    }

我正在寻找的是存储每个控制器当前状态的最干净方法,以便点击“返回”状态。按钮将使用最初传入的任何参数重新加载控制器。

我尝试在我的模块run bootstrap方法中使用以下代码,但是当我点击链接显示订单时,它会遍历一个名为order-edit的状态,然后尝试获取订单从数据库通过REST。

如果找不到订单URI,我会在错误页面中正确显示HTTP 404错误,当我点击&#39;返回&#39;按钮它重新触发以前的REST动作ad-infinitum,这不是我想要的。

我想要发生的事情就是“回归”&#39;按钮带我回到显示我的订单在表格中的页面的两个步骤。要做到这一点,我可能必须手动存储当前状态,以便返回将重新加载正确的状态,但我担心这可能会使许多控制器变得混乱,使其难以实现。

$rootScope.previousState;
$rootScope.previousStateParams;
$rootScope.currentState;

$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
    $rootScope.previousState = from.name;
    $rootScope.previousStateParams = fromParams;
    $rootScope.currentState = to.name;
    console.log('Previous state:' + $rootScope.previousState);
    console.log('Current state:' + $rootScope.currentState);
});

我想避免在我的所有控制器中手动设置当前状态,因为如果“返回”中指定的状态,应用程序可能很容易在错误的控制器中结束。按钮未设置为正确的状态。

我希望这一切都有意义吗?

0 个答案:

没有答案