使用ui-router显示404错误页面时如何更改url

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

如果我会做这样的事情:

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

url将更改为/404 。 如何在错误的URL上显示错误信息而不改变实际的URL?

有这种情况的解决scheme。 我们将使用1)一个ui-router原生function和2)一个configuration设置。 这里可以看到一个可行的例子 。

1)ui路由器状态定义的本地特征是:

url是不需要的。 国家可以在没有代表位置的情况下被定义。

2)configuration设置是:

  • otherwise()为无效路由 ,哪个参数不一定是一个string与默认的url,但也可以是一个函数(引用)

pathstring| 函数您要redirect到的urlpath或返回urlpath的函数规则。 函数版本传递了两个参数:$ injector和$ location

解决scheme:这两个组合。 我们将有没有 url和自定义, 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#0.2.15你可以使用$state.go()并发送选项来不更新位置:

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