Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call canDeactivate in Angular when logout is clicked

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.

like image 806
Gowtham Raj J Avatar asked Jan 10 '18 11:01

Gowtham Raj J


People also ask

Can deactivate Guard is invoked when?

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.

What is the difference between CanActivate and CanDeactivate in angular?

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.

How do you use CanDeactivate?

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.

What is CanDeactivate?

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.


1 Answers

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

like image 166
nayakam Avatar answered Sep 28 '22 13:09

nayakam