使用 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()
用于无效路由,该参数不必是带有默认 url 的字符串,也可以是一个函数 (cite):
-
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();
});
检查此工作示例