0

I am trying to change the route to the default (otherwise) route when an error occures. The otherwise route is set to display 404 Error page. Does somebody know how to do it? The url should stay as it is, that is why I cannot use redirect to /404.

Angular version: 1.6.2

So far I came with this:

// 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
        }
    });
}]);

No error is shown and the 404 Controller is not loaded.

Michal Majernik
  • 395
  • 1
  • 3
  • 11
  • 2
    you either need to change the url, or have a nested view. But even then, I don't believe `ngRoute` is advanced enough to handle such routing without changing the url, unlike [`ui.router` version](https://stackoverflow.com/questions/23298021/how-not-to-change-url-when-show-404-error-page-with-ui-router/32278981) – Aleksey Solovey Jul 10 '18 at 09:53
  • @AlekseySolovey Thanks for your comment. It haven't found any good solution so I used just a simple ng-if for that. If the data is not loaded I show the 404 page content. – Michal Majernik Jul 11 '18 at 06:52

0 Answers0