单击注销时如何在 Angular 中调用 canDeactivate

gow*_*j j 7 javascript angular angular-router-guards angular-router

在我当前的注销呼叫中,我有这样的事情:

 getLogoutConfirmation(){
   // get confirmation in modal and perform logout
   // redirect to login page
 }
Run Code Online (Sandbox Code Playgroud)

问题是,当执行注销并调用重定向到登录时,会在该路由上调用 canDeactivate 防护,但用户已经注销。

那么如何在执行注销之前调用 canDeactivate 守卫并在用户不想离开时取消注销操作。

谢谢。

小智 1

只需在注销调用中调用 CanDeactivate ,然后您在那里进行逻辑操作:

canDeactivate() {
  if(confirm('Leave and logout ?') {
    this.loginService.logout();
    this.router.navigate('');
    return true;
  } else {
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

canDeactivate 只是接口的实现,您可以像调用任何函数一样调用它