Javascript 如何使用ui路由器显示错误页面,从以前的状态导航时更改url?

Javascript 如何使用ui路由器显示错误页面,从以前的状态导航时更改url?,javascript,angularjs,angular-ui-router,Javascript,Angularjs,Angular Ui Router,我使用的是ui路由器1.0.0和angularjs 1.4.2。我想实现显示错误页面的常规行为: 我正在看国家/富 我点击/bar,解析结果是500错误(后端) url更改为/bar并显示错误页面(url仍然为/bar) 当然,如果我在浏览器中直接键入/bar url,我希望看到相同的页面。历史记录按钮也应按预期工作。 我尝试了以下代码,但url没有改变,仍然使用/foo $transitions.onError({}, function () { $state.go('erro

我使用的是ui路由器1.0.0和angularjs 1.4.2。我想实现显示错误页面的常规行为:

  • 我正在看国家/富
  • 我点击/bar,解析结果是500错误(后端)
  • url更改为/bar并显示错误页面(url仍然为/bar)
当然,如果我在浏览器中直接键入/bar url,我希望看到相同的页面。历史记录按钮也应按预期工作。 我尝试了以下代码,但url没有改变,仍然使用/foo

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

这怎么可能呢?

使用您的示例URL:

  • “/foo”-正常、功能状态
  • “/bar”-由于错误而拒绝解析的状态
如果直接导航到“/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 });
}

使用您的示例URL:

  • “/foo”-正常、功能状态
  • “/bar”-由于错误而拒绝解析的状态
如果直接导航到“/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 });
}

您是否试图在状态的resolve方法上执行此操作?否则,为什么不直接使用$state。转到then/catch中的所述状态。我确实使用resolve,并假设来自后端的响应为500。然而,在我的应用程序中为我的所有解析写一个then/catch会有太多的重复和错误。这就是为什么您更喜欢$transitions.onError。是否尝试在状态的resolve方法上执行此操作?否则,为什么不直接使用$state。转到then/catch中的所述状态。我确实使用resolve,并假设来自后端的响应为500。然而,在我的应用程序中为我的所有解析写一个then/catch会有太多的重复和错误。这就是为什么我更喜欢$transitions.onError。