【问题标题】:How to avoid navigating to another page while doing something in current page in Angular如何在Angular的当前页面中执行某些操作时避免导航到另一个页面
【发布时间】:2021-10-12 22:14:20
【问题描述】:

目前,我正在一个 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 中,我看不到用户确认。

【问题讨论】:

    标签: angular router onbeforeunload candeactivate navigationstart


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      使用async - await 方法

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-17
        • 1970-01-01
        • 1970-01-01
        • 2021-09-17
        • 2019-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多