1

目前,我在一个 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;
  }

}

第一,我得到确认,但已经导航到点击的页面rouetlink

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

4

2 回答 2

2

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

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

于 2021-08-09T07:43:30.493 回答
0

使用async - await方法

所以你可以导航部分等到过程/方法完成

于 2021-08-09T09:00:00.570 回答