渲染404页,无角JS重定向 [英] render 404 page without redirecting in angular js

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

问题描述

我使用ui.router&安培; ngResource与AngularJS,&安培;我的问题是:

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

我如何显示404没有重定向到它如用户键入 HTTP://www.example .COM /错误的页面名称,他应该只显示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-tempalte hidden" ng-class="{'hidden': !notFound}">
  <h2>Not Found!</2>
</div>

在CSS:

.hidden
{
  display: none !important;
}

和错误处理的服务(可选)

and 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页,无角JS重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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