0

My CanDeactivateGuard not always fires when I click browser back button. I can't find the reason. Could you take a look at my code, and give me advice?

Guard:

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<SignupComponent> {
  canDeactivate(component: SignupComponent): boolean {
    if (!component.canDeactivate()) {
      if (confirm("You have unsaved changes! If you leave, your changes will be lost.")) {
        return true;
      } else {
        return false;
      }
    }
    return true;
  }
}

Method in SignupComponent:

canDeactivate() {
    if (this.activeStep == 'step1' || this.activeStep == 'step5') {
      return true;
    } else {
      return false;
    }
  }

Routing:

...
  {
    path: 'signup/:nickname',
    component: SignupComponent
  },
  {
    path: 'signup',
    component: SignupComponent,
    canDeactivate: [CanDeactivateGuard]
  },
...
pelcomppl
  • 575
  • 2
  • 6
  • 16
  • Browser back button doesn't really work well with guards. You should use a different approach like this: https://stackoverflow.com/questions/40381814/how-do-i-detect-user-navigating-back-in-angular2. Or add a host listener for `onbeforeunload ` event. – Roberto Zvjerković Dec 06 '18 at 14:46

1 Answers1

0

Add it to the other routes as well

  {
    path: 'signup/:nickname',
    component: SignupComponent
    canDeactivate: [CanDeactivateGuard]
  },
  {
    path: 'signup',
    component: SignupComponent,
    canDeactivate: [CanDeactivateGuard]
  },
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80