繁体   English   中英

如何使用ui-router显示错误页面,在从先前状态导航时更改URL?

[英]How to display an error page with ui-router, changing the url when navigating from a previous state?

我正在使用ui-router 1.0.0和angularjs 1.4.2。 我想实现显示错误页面的常规行为:

  • 我正在查看州/ foo
  • 我点击/ bar,解决方案最终出现500错误(后端)
  • 网址更改为/ bar并显示错误页面(网址仍为/ bar)

当然,如果我在浏览器中直接输入/ bar url,我希望看到同一页面。 历史按钮也应按预期工作。 我已经尝试了以下代码,但网址没有改变,与/ foo保持一致。

$transitions.onError({},
  function () {
    $state.go('error', null, { location: false });
  }
);

怎么可能?

使用示例网址:

  • '/ foo' - 正常,运作状态
  • '/ bar' - 由于500而拒绝解决的州

如果直接导航到'/ bar',该功能应该已按预期工作。 该URL将为“/ bar”,您可以在该页面上显示错误状态

如果从'/ foo'导航,那么我没有找到任何方法告诉ui-router如果解决方案被拒绝,将URL更改为目标状态的URL,但我找到了解决方法:

  • onError ,手动将URL更改为目标状态的URL。
  • 这将触发到同一目标的新转换,这将再次导致onError,因此我们需要确保如果目标路径已经与当前路径匹配,我们不会执行另一个URL更改(这里可能存在无限循环)

例如:

const targetState = transition.targetState().name;
const targetHref = $state.href(targetState);
const currentPath = $location.path();

if (targetPath !== currentPath) {
    //  This triggers a new transition to the same state, but with the URL already changed
    // (so that the URL represents the target state even if the transition is rejected)
    $location.path(targetPath);
} else {
    // In this case we're on the target URL for this failed transition, and we
    // show our error state while leaving the user's intended URL in place
    $state.go('error', null, { location: false });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM