Use Guard canDeactivate to call function on refresh & reroute

1.1k views Asked by At

I have a guard set in place in order to show a warning when the user switches and/or refreshes the page. I also implemented a way to call the function ngOnDestroy when these actions are made.

Problem: When the user refreshes trys to leave the website, the popup is show correctly, but no matter what he chooses, ngOnDestroy is called. So, the function is trigger even if he doesn't refresh the page. I want to implement a way that the function is only called when he accepts the default alert and the page does indeed refresh.

show-quiz.module.ts
ngOnInit(): void {
  window.onbeforeunload = () => this.ngOnDestroy();   //Call ngOnDestroy when the user closes/switches the tab
}

//Stop timer when the component is destroyed
ngOnDestroy(): void {
  // If the user is in the middle of the exam, save the data
  if (!this.end) {
    this.checkAnswers();
  }
}

//@HostListener allows us to also guard against browser refresh, close, etc.
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
  // insert logic to check if there are pending changes here;
  // returning true will navigate without confirmation
  // returning false will show a confirm dialog before navigating away
  return this.end;
}
app-routing.module.ts
{ path: 'show-quiz', component: ShowQuizComponent, canDeactivate: [PendingChangesGuard] }
pending-changes.guard.ts
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    // if there are no pending changes, just allow deactivation; else confirm first
    return component.canDeactivate() ?
      true :
      // NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
      // when navigating away from your angular app, the browser will show a generic warning message
      // see http://stackoverflow.com/a/42207299/7307355
      confirm('ATENÇÃO: Alterações podem não ter sido guardadas. Tem a certeza que deseja sair?');
  }
}
0

There are 0 answers