In my current logout call, I have something like this:
getLogoutConfirmation(){
// get confirmation in modal and perform logout
// redirect to login page
}
Issue is, when logout is performed and redirect to login is called, the canDeactivate guard is called on that route, but User has already been logged out.
So how do I call canDeactivate guard before the logout is performed and cancel logout action if user doesn't want to leave.
Thanks.
What is CanDeactivate Guard. The Angular CanDeactivate guard is called, whenever we navigate away from the route before the current component gets deactivated. The best use case for CanDectivate guard is the data entry component.
CanActivate : Checks route navigation before the component is loaded. CanActivateChild : Checks route children navigation before the component is loaded. CanDeactivate : Checks navigation from the current route eg leaving the partially filled form. Resolve : Resolve loads/ retrieves data before the route is activated.
You can use the CanDeactivate guard to prevent usesr from accidentally leaving a route/page in your application for example if such page contains a text editor with unsaved changes or an unsubmitted form.
CanDeactivatelinkInterface that a class can implement to be a guard deciding if a route can be deactivated. If all guards return true , navigation continues. If any guard returns false , navigation is cancelled.
You should navigate to login page based on getLogoutConfirmation()
. if you didn't navigate away then CanDeactivate
wouldn't be activated.
Otherwise, Guard canDeactivate is get invoked when navigating away from the current view or route within your angular app. You could check and for getLogoutConfirmation within canDeactivate then decide to continue or cancel navigation. CanDeactivate guard can be used to handle the unsaved change, check permission and clean up the component. This doesn't handle the external navigations such as browser refreshes or closing . You need to use @HostListener('window:beforeunload')
for these cases
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With