Angular 如何避免在当前页面中执行某些操作时导航到另一个页面

How to avoid navigating to another page while doing something in current page in Angular

目前,我正在 HTML 页面上做一些事情。如果我错误地点击了另一个页面,它会在没有得到任何用户确认的情况下重定向到那个页面。

这是我的组件。

export class MyComponent {    
 constructor(private router: Router, public closeModal: ModalRef,){
 // 1st thing i tried
   router.events.subscribe((val) => {       
      if (val instanceof NavigationStart) {
        const config = {
          class: 'modal-lg, modal-danger',
          keyboard: false,
          animated: true,
          ignoreBackdropClick: true,
          initialState: {
            title: 'Are you sure you want to leave',
            content: `Are you sure you want to leave the page?`
          }
        };
        this.closeModal = this.modalService.show(DeleteConfirmModalComponent, config);
        this.closeModal.content.closeBtnName = 'Close';
      }
    });
}

// 2 thing i tried

@HostListener('window:beforeunload', ['$event'])
  canDeactivate(event: BeforeUnloadEvent): void {
   
    const config = {
      class: 'modal-lg, modal-danger',
      keyboard: false,
      animated: true,
      ignoreBackdropClick: true,
      initialState: {
        title: 'Are you sure you want to leave',
        content: `Are you sure you want to leave the page?`
      }
    };
        this.closeModal = this.modalService.show(DeleteConfirmModalComponent, config);
        this.closeModal.content.closeBtnName = 'Close';

    event.returnValue = false;
  }

}

在第 1 天我收到了确认,但已经导航到点击的页面 rouetlink

在 2 中我看不到用户确认。

RouteGuard 的方法CanDeactivate正是您所需要的。

如果文档太枯燥,有一篇文章可以帮助:Angular 10 CanDeactivate

使用async - await方法

因此您可以将导航部分等到 process/method 完成