I am struggling a bit on a particular use case with Angular2 and the router.
Let's say we have 3 routes. Home, List and Profile.
"Profile" is a guarded route : user has to be authenticated to access this route.
If user is on "Profile" page and logs out, I want to be able to detect that he is not allowed anymore to be on the current page, and redirect him to "Home" page.
However if he is on "List" page and logs out, I don't want to do anything (user is allowed to stay here as it's not a guarded route).
Do someone know how I can achieve that, assuming that I have many routes and I want to avoid to put this "user-is-allowed" logic in each component ?
Summary
In my case I like to give my user's access to the Guarded routes by checking the validation of a token I save to local storage. So if I log them out I remove the token along with any data I currently have in local storage. You can use this function in each route.
I create a service for authentication. You could create two different services, or two different functions. Really you have a lot of options. Here is one option.
Solution
To logout and redirect,
You could use this function in each one of your components. Or pages. Basically redirect the route if the user is on the profile page. but if the user is not on a page or route that needs to be redirected then remove the
From the function so the user is not redirected.
So you could have two services
Then in your pages that you want to log the user out but leave them on the same page use this service
So when the use the logout function it wont redirect.
Then to redirect when the user logs out add this service like this,
And of course any component you include the service too you call the correct
logout function
in yourhtml
like this,or