Angular.js:更改$ routeChangeError上的路线

时间:2018-07-10 09:25:23

标签: angularjs angular-routing

我正在尝试在发生错误时将路由更改为默认(否则)路由。否则,路由设置为显示404错误页面。有人知道怎么做吗?网址应保持原样,这就是为什么我不能使用重定向到/ 404的原因。

角度版本:1.6.2

到目前为止,我来了:

// inherit function is copied from angular-route.js
function inherit(parent, extra) {
    return angular.extend(Object.create(parent), extra);
}
app.config(['$routeProvider', '$locationProvider', function($routeProvider, locationProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('!');

    $routeProvider
        .when('index/:param1/:param2?', {
            controller: 'IndexController',
            templateUrl: 'Resources/Private/JavaScript/Templates/View/Index.html',
            resolve: {
                ajaxData: ['$q', function ($q) {
                    var deferred = $q.defer();
                    //...
                    //on error following reject is called
                    deferred.reject({
                        status: 404
                    });
                    //...
                }]
            }
        })
        .otherwise({
            controller: '404Controller',
            templateUrl: 'Resources/Private/JavaScript/Templates/View/404.html'
        });
}]);

app.run(['$rootScope', '$route', 'HttpError', function ($rootScope, $route, HttpError) {
    $rootScope.$on('$routeChangeError', function (evt,current,previous,rejection) {
        if (rejection.hasOwnProperty('status') && rejection.status === HttpError.NOT_FOUND) {
            var last = $route.current,
                errorRoute = $route.routes[null],
                errorRouteInstance = inherit(
                    errorRoute,
                    {
                        params: {},
                        pathParams: {}
                    }
                );

            errorRouteInstance.$$route = errorRoute;
            errorRouteInstance.loadedTemplateUrl = errorRoute.templateUrl;

            $route.current = errorRouteInstance;
            $rootScope.$broadcast('$routeChangeSuccess', errorRouteInstance, last);
        } else {
            //OR DO SOMETHING ELSE
        }
    });
}]);

未显示任何错误,并且未加载404控制器。

0 个答案:

没有答案