使用AngularJS路由加载404状态页

6
我正在使用 AngularJSui-router,以下是能够捕获404错误并加载404模板的代码:
$urlRouterProvider.otherwise(function($injector, $location){
  $injector.invoke(['$state', function($state) {
    $state.go('404');
  }]);
}); 

它保持URL不变,而不是重定向,但显示404模板:
.state('404',
{
    views: {
        'body': {
            templateUrl: 'partials/404.html',
        }
    }
});

通常情况下,使用如下代码重定向到根状态: $urlRouterProvider.otherwise('/');

然而,当关闭HTML5模式并访问根URL时,例如http://www.domain.com/app/,它会加载404状态而不是重定向到http://www.domain.com/app/#/

如何保留上述404状态代码,但在访问初始页面时将其重定向到Hashbang?因此,仅在请求不是主页时才加载404状态?

我无法使用$stateNotFound$stateChangeSuccess,需要一种方法来检查是否是主页请求,并在配置设置本身内切换/state.404之间的方式。


你能提供更多的代码细节吗? - nikudale
你想要一个同时支持HTML5模式开启和关闭的解决方案吗?如果你只发布一种模式的应用程序,讨论可能的解决方案会更容易。我至少知道一种解决方案。 - stanleyxu2005
2个回答

3
因此,类似以下内容是可以工作的(尽管有些改进空间)。
$urlRouterProvider.otherwise(function($injector, $location){
    $injector.invoke(['$state', function($state) {
        if( $location.$$path == '')
            $state.go('home'); // redirect to /#/
        else
            $state.go('404'); // else go to 404 state
    }]);
});

但是有没有更好的方法来处理这个问题呢?

0
使用一个 httpErrorResponseInterceptor!当发生 httpResponse 时,它将被触发。以下是一个示例。
angular
    .module('myApp')
    .factory('httpErrorResponseInterceptor', ['$q', '$state', function ($q, $state) {
     return {
         responseError: function error(response) {
             switch (response.status) {
                 case 404:
                     $state.go('404');
                     break;

                 default:
                     console.log("Unhandled HTTP error:", response);
             }

             return $q.reject(response);
         }
     };
 }
]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接