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

max*_*old 17 angularjs angular-ui-router

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

如果我会做那样的事情:

$urlRouterProvider.otherwise('404');
$stateProvider
    .state('404', {
        url: '/404',
        template: error404Template
    });
Run Code Online (Sandbox Code Playgroud)

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

Rad*_*ler 38

这种情况有解决方案.我们使用1)一个ui-router本机功能和2)一个配置设置.这里可以看到一个工作的例子.

1)ui-router状态定义的本机特性是:

url是没有必要的.可以定义国家而不在地点代表.

2)配置设置为:

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

解决方案:这两者的结合.我们state 没有 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();
});
Run Code Online (Sandbox Code Playgroud)

在这个工作示例中检查所有内容

  • 精彩解决方案 谢谢@Radim (2认同)

ilo*_*ett 15

截至ui-router#0.2.15您可以使用$state.go()和发送选项不更新位置:

$urlRouterProvider.otherwise(function($injector) {

  var $state = $injector.get('$state');

  $state.go('404', null, {
    location: false
  });

});
Run Code Online (Sandbox Code Playgroud)