我正在使用 ui-router 1.0.0 和 angularjs 1.4.2。我想实现显示错误页面的通常行为:
- 我正在查看状态/foo
- 我点击/bar,其解析最终出现 500 错误(后端)
- url 更改为/bar 并显示错误页面(url 仍为/bar)
当然,如果我在浏览器中直接输入/bar url,我希望看到相同的页面。历史记录按钮也应该按预期工作。 我已经尝试了以下代码,但 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 });
}
关于javascript - 如何使用 ui-router 显示错误页面,从先前状态导航时更改 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762321/