使用 ui-router 显示 404 错误页面时如何不更改 url [英] How not to change url when show 404 error page with ui-router

查看:28
本文介绍了使用 ui-router 显示 404 错误页面时如何不更改 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示 404 错误页面,但我也想在位置保存错误的 url.

I want to show 404 error page, but also I want to save wrong url in location.

如果我会这样做:

$urlRouterProvider.otherwise('404');
$stateProvider
    .state('404', {
        url: '/404',
        template: error404Template
    });

url 将更改为 /404.如何在不更改实际网址的情况下在错误网址上显示错误消息?

url will change to /404. How I can show error message on wrong urls without changing actual url?

推荐答案

有针对这种情况的解决方案.我们将使用 1) 一项 ui-router 原生功能和 2) 一项配置设置.可以观察到工作示例此处.

There is solution for this scenario. We'd use 1) one ui-router native feature and 2) one configuration setting. A working example could be observed here.

1) ui-router 状态定义的一个原生特性是:

1) A native feature of ui-router state definitions is:

不需要 url.可以在没有位置表示的情况下定义状态.

The url is not needed. State could be defined without its representation in location.

2) 一个配置设置是:

2) A configuration setting is:

  • otherwise() for invalid routes, which parameter does not have to be a string with default url, but could be a function as well (cite):

路径 字符串 |Function 要重定向到的 url 路径或返回 url 路径的函数规则.函数版本传递了两个参数:$injector 和 $location

path String | Function The url path you want to redirect to or a function rule that returns the url path. The function version is passed two params: $injector and $location

解决方案:这两者的结合.我们会有 state without url 和自定义 otherwise:

Solution: combination of these two. We would have state without url and custom otherwise:

$stateProvider
  .state('404', {
    // no url defined
    template: '<div>error</div>',
  })

$urlRouterProvider.otherwise(function($injector, $location){
   var state = $injector.get('$state');
   state.go('404');
   return $location.path();
});

检查此工作示例

这篇关于使用 ui-router 显示 404 错误页面时如何不更改 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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