【问题标题】:How not to change url when show 404 error page with ui-router使用 ui-router 显示 404 错误页面时如何不更改 url
【发布时间】:2014-06-11 10:58:35
【问题描述】:

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

如果我会这样做:

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

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

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

    这种情况有解决方案。我们将使用 1) 一项 ui-router 原生功能和 2) 一项配置设置。可以观察到working example here

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

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

    2) 配置设置为:

    路径 字符串 | Function 要重定向到的 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();
    });
    

    检查working example中的所有内容

    【讨论】:

      【解决方案2】:

      ui-router#0.2.15 开始,您可以使用$state.go() 并发送选项来不更新位置:

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

      【讨论】:

      • 谢谢!这对于动态 url 的 'otherwise' 和 '$stateChangeError' 拦截非常有效。
      猜你喜欢
      • 2023-01-29
      • 1970-01-01
      • 2013-08-13
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多