渲染 404 页面而不在 Angular js 中重定向 [英] render 404 page without redirecting in angular js

查看:34
本文介绍了渲染 404 页面而不在 Angular js 中重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ui.router &ngResource 与 AngularJS, &我的问题是:

I am using ui.router & ngResource with AngularJS, & my question is :

如何在不重定向的情况下呈现 404 例如用户键入 http://www.example.com/wrong-page-name ,他应该只看到 404 页面,并且 URL 不应该改变.

How do I RENDER 404 without redirecting to it e.g A user typed http://www.example.com/wrong-page-name , he should just be shown the 404 page, and the URL shouldn't change.

目前我是这样做的,但它会重定向

Currently this is how I did it but it redirects

    angular.module('app')
   .run(['$rootScope', '$state', function($rootScope, $state) {

            $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
                if(error.status === 404) {
                    $state.go('innerPages.page', {slug:"not-found"});
                }
            });
    })
    .config(['$stateProvider','$urlRouterProvider', function($stateProvider, $urlRouterProvider) {

            $stateProvider.state('innerPages.page', {
                url: ':slug',
                views : {
                    'content@':{
                        templateUrl : '...',
                        controller : 'pageController'
                    },
                    'pageHeader@' : {
                        templateUrl : "...",
                        controller : 'pageController'
                    }
                },
                resolve:{
                    page: ['pageService', '$stateParams', function (pageService, $stateParams) {
                        return pageService.get({slug:$stateParams.slug}).$promise;
                    }]
                }
            });

        }]);

感谢您的帮助!

推荐答案

为什么不直接显示404模板?

Why don't you just show the 404 template?

<any ng-view ng-class="{'hidden': notFound}"></any>
<div class="not-found-template hidden" ng-class="{'hidden': !notFound}">
  <h2>Not Found!</h2>
</div>

对于 css:

.hidden
{
  display: none !important;
}

并添加错误处理服务(可选)

And add a service for error handling (optional)

 angular.module('app').service('Errors', function ($rootScope) {
  this.handle = function (error, status) {
    // not found
    switch (status) {
      case 404:
        alert('Sorry! the page was not found.');
        // This is the required line for showing 404 template
        $rootScope.notFound = true;
        break;
      case 500:
        alert('Sorry! Error connecting to server.');
        break;
      case 403:
        $location.path('/login');
        break;
      default:
        alert('Sorry! Error connecting to server.');
    }
  }
});

这篇关于渲染 404 页面而不在 Angular js 中重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆