如何使用 ui 路由器防止 angular 2/4 项目中的状态更改?

How to prevent a state change in angular 2/4 project using ui router?

当用户切换到另一个状态或关闭页面时,弹出一个window询问用户是否真的要离开当前页面。 如果用户选择不离开,则阻止状态转换。

有办法吗?

注意:项目使用Angular2/4ui-路由器。

我知道在 angular 1.x 中您可以使用 $stateChangeStart 事件并执行 event.preventDefault() 来停止状态更改。 Angular 2/4 中是否有类似的内容?

您可以像这样收听 unloadbeforeunload 事件:

export class AppComponent {
  @HostListener('window:unload', [ '$event' ])
  unloadHandler(event) {
    // open popup
  }

  @HostListener('window:beforeunload', [ '$event' ])
  beforeUnloadHandler(event) {
    // open popup
  }
}

尝试使用UI-ROUTERTransitionService及其onBefore()方法。

UI-ROUTER's site 所述:

Registers a transition lifecycle hook, which is invoked before a transition even begins. This hook can be useful to implement logic which prevents a transition from even starting, such as authentication, redirection

...

The hook's return value can be used to pause, cancel, or redirect the current Transition.

...

false: the transition will be cancelled

停止转换:

transitionService.onBefore({ to: 'home' }, (trans: Transition) => {
  // put here you conditional logic
  if ('the user choose not to leave') {
    return false;
  }
  // if you want to redirect to different location use:
  // trans.router.stateService.target("home.dashboard"));
});