首页 > 解决方案 > 如何使用 canDeactivate 与不在 ts 文件中的路由?

问题描述

我已经实现了防护并将其添加到相关路由中,例如路径: ]"quotes", children: [ { path: "", component: QuotesComponent},
{ path: "create", component: CreateQuoteComponent, canDeactivate: [CanDeactivateGuard]},
{ path: ":id", component: CreateQuoteComponent, canDeactivate: [CanDeactivateGuard]}

我还在相关组件中添加了一个条件,例如:

canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
    let agreeToLeave = false;
    if (this.changesSaved === false) {
      let message = 'You have not saved your current work and will lose changes. Are you want to proceed?';
      let data = { 'message': message, 'toShowCancel': true, 'buttonYesCaption': 'Yes', 'buttonNoCaption': 'No' };
      const dialogRef = this.dialog.open(YesNoComponent, {
        width: '600px',
        height: '250px',
        data: data
      });

      dialogRef.afterClosed().subscribe(result => {
        if (result) {
          agreeToLeave = true;
          return true;
        }
      });
      return agreeToLeave;
    }else{
      return true;
    }
  }

每次单击任何按钮时,我都会看到模式窗口询问,但如果单击“是”,它不会转到相关页面。

同样,在我的情况下,所有路由都在 html 文件中,例如:

<mat-list-item [routerLink]="['/events']" routerLinkActive="activated">
    <button mat-icon-button>
      <mat-icon>comment</mat-icon>
    </button>

非常感谢提前![在此处输入图像描述] 1

标签: angularangular-ui-routerangular-material

解决方案


afterClosed()是一个异步操作。事实上,它是一个 Promise。在模态关闭之前返回false默认值。agreeToLeave与其返回布尔值,不如简单地返回 Promise 本身。

canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
    if (this.changesSaved) {
      return true;
    }

    const message = 'You have not saved your current work and will lose changes. Are you want to proceed?';
    const data = { 'message': message, 'toShowCancel': true, 'buttonYesCaption': 'Yes', 'buttonNoCaption': 'No' };
    const dialogRef = this.dialog.open(YesNoComponent, {
      width: '600px',
      height: '250px',
      data: data
    });

    return dialogRef.afterClosed(); // if necessary map to boolean with map operator
  }

编辑:为您的代码添加了一些改进


推荐阅读