转到错误状态并将URL保持为生成错误的状态

时间:2014-09-19 09:31:14

标签: angularjs angular-ui-router

我正在使用它来捕获错误并重定向到错误页面

module.run(function ($state, $rootScope, translateService) {
    $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
        $state.go("app.error");
    });
});

但是这会转移到错误状态并更改URL。我想转到错误页面,并将URL保留在页面中并显示错误。

我已尝试使用位置选项$state.go("app.error", null, { location: false }),但它保留了我来自的州的网址,而不是有错误的网址。

我可以以某种方式转到错误状态并保留URL或转到错误状态,然后将网址更改回toState的网址吗?

3 个答案:

答案 0 :(得分:3)

我通过将错误信息发送到错误状态然后在那里设置$ location.path的URL来解决它。

module.run(function ($state, $rootScope) {
    $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
        $state.get("app.error").$error = {
            toState: toState,
            toParams: toParams,
            fromState: fromState,
            fromParams: fromParams,
            message: error.message,
            stack: error.stack
        };

        $state.go("app.error");
    });
});

module.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider.state("app.error", {
        url: "/error",
        resolve: {
            error: function () {
                return this.self.$error;
            }
        },
        templateUrl: "app/error.tpl.html",
        controller: function ($state, $scope, $log, $location, error) {
            if (error) {
                $location.path($state.href(error.toState, error.toParams).replace(/^#/, ""));
                $log.error(error.message, error.stack);
            }

            $scope.error = error;
        }
    });
});

答案 1 :(得分:0)

我认为这就是诀窍(我前段时间发现了这个伎俩,没有记录):

$rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
    event.preventDefault();

    $state.go("app.error", {}, { location: false });
});

https://github.com/angular-ui/ui-router/wiki 看看关于$ stateChangeError的部分

答案 2 :(得分:0)

要添加到已接受的答案,我做了一个小的更改,允许我保留错误网址,但尝试在用户尝试刷新时转到主页(或任何你想要的状态):

controller: function ($state, $scope, $log, $location, error) {
        if (error) {
            $log.error(error.message, error.stack);
        }else{
            $state.go('app'); // or app.home or whatever
        }

        $scope.error = error;
    }