0

Looks like canDeactivate doesn't intercept window.location.replace. I have a service call in my component that replaces the current url:

window.location.replace('path');

I have a guard that looks like this but it is not called when 'window.location.replace' happens:

public canDeactivate(
        component: MyFormComponent
    ): Observable<boolean> {
        return of(false);
}

Is this something that I missed or maybe this is an angular limitation?

SimonD
  • 1,441
  • 2
  • 18
  • 30

1 Answers1

1

This is normal.

window is outside of the angular context. It's like if you change URL by hand. Angular will not prevent this redirection, because it's done by the browser and not angular. CanDeactivate Guards only apply to angular navigation events

If you want your guard to be triggered you will have to use the Angular Router to change your URL.

Or the other solution is to use a @HostListener('window:beforeunload', ['$event']) to listen to the window:beforeunload event. See onbeforeunload confirm dialog not showing when angular2 @HostListener is used for more details

Valentin Roche
  • 284
  • 2
  • 5