Reputation: 24945
routerCanDeactivate()
successfully prevents navigation away from component.
routerCanDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction)
{
return confirm("Do you want to discard unsaved changes ?");
}
But if navigation is caused by Browser's back
button or any other history.back()
trigger,
then it doesn't keep the history intact and triggers popState
on every trigger and eventually navigates to Browser's homepage (tested on Chrome).
EDIT:
I saved current component's URL in a variable currentLocation
and
tried to manipulate history
with history api
but
just couldn't figure out the right order of api calls required to keep it intact.
routerCanDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) {
history.replaceState(null,null, this.currentLocation);
history.forward();
return confirm("Do you want to discard unsaved changes ?");
}
Upvotes: 1
Views: 819
Reputation: 24945
Due to window.onpopstate
triggering at every back button click,
I thought that a pushState
will be required. But that wasn't the case, and following code works perfectly.
routerCanDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) {
if(confirm("Do you want to discard unsaved changes ?")){
return true;
}
else {
history.forward();
return false;
}
}
But it would be nice if somebody could explain what is happening because I don't have much knowledge of history api
.
Upvotes: 1