简体   繁体   English

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

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

I'm using ui-router 1.0.0 and angularjs 1.4.2. 我正在使用ui-router 1.0.0和angularjs 1.4.2。 I'd like to implement the usual behaviour of displaying error pages : 我想实现显示错误页面的常规行为:

  • I'm viewing the state /foo 我正在查看州/ foo
  • I click on /bar, for which a resolve ends up with a 500 error (backend) 我点击/ bar,解决方案最终出现500错误(后端)
  • The url changes to /bar and the error page is displayed (url is still /bar) 网址更改为/ bar并显示错误页面(网址仍为/ bar)

Of course, if I type directly the /bar url in my browser, I'd like to see the same page. 当然,如果我在浏览器中直接输入/ bar url,我希望看到同一页面。 History buttons should also work as expected. 历史按钮也应按预期工作。 I've tried the following code but the url doesn't change, staying with /foo. 我已经尝试了以下代码,但网址没有改变,与/ foo保持一致。

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

How is that possible ? 怎么可能?

Using your example URLs: 使用示例网址:

  • '/foo' - normal, functioning state '/ foo' - 正常,运作状态
  • '/bar' - state for which the resolve is rejected due to a 500 '/ bar' - 由于500而拒绝解决的州

The functionality should already work as expected if navigating directly to '/bar'. 如果直接导航到'/ bar',该功能应该已按预期工作。 The URL will be '/bar', and you can show your error state on that page 该URL将为“/ bar”,您可以在该页面上显示错误状态

If navigating from '/foo', then I haven't found any way to tell ui-router to change the URL to that of the target state if a resolve is rejected, but I did find a workaround: 如果从'/ foo'导航,那么我没有找到任何方法告诉ui-router如果解决方案被拒绝,将URL更改为目标状态的URL,但我找到了解决方法:

  • In onError , manually change the URL to that of the target state. onError ,手动将URL更改为目标状态的URL。
  • This will trigger a new transition to the same target, which will again cause an onError, so we need to ensure we don't perform another URL change if the target path already matches the current path (there's potential for an infinite loop here) 这将触发到同一目标的新转换,这将再次导致onError,因此我们需要确保如果目标路径已经与当前路径匹配,我们不会执行另一个URL更改(这里可能存在无限循环)

For example: 例如:

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