如何在不包含在ts文件中的路由中使用canDeactivate?

时间:2019-08-29 09:21:24

标签: angular angular-ui-router angular-material

我已经实现了防护并将其添加到相关的路由中,例如路径:"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>

在此先感谢![enter image description here] 1

1 个答案:

答案 0 :(得分:0)

您的afterClosed()是异步操作。实际上,这是一个承诺。在关闭模态之前,您使用默认值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
  }

编辑:对代码进行了一些改进