Why does refreshing on guarded page redirect me to root, and not my specified redirection?


I am using Angular 2 framework. I have set up my app-routing module so that I am directed to a sign on page immediately (using pathmatch ‘full’ and redirectTo:’signOn’. All other routes in my app-routing module have canActivate: CanActivateViaAuthGuard. This only lets the user navigate to the other links if they have signed in. This works correctly, and once signed in the functionality is fine. The user can even sign out and is returned to the home page.

However if the user is signed in and then refreshes the page, this technically sets the boolean (that is allowing them to navigate) back to false and it tries to pull up the root page, localhost:4020, which is empty. I need it to route to localhost:4020/signOn like it does initially if the user refreshes the page.

Any advice?

Example of routes in my paths variable:

{ path: '', redirectTo: 'dash', pathMatch: 'full' },
{ path: 'signOn', component: SignOnComponent},
{ path: 'dash', component: 'DashComponent', canActivate: [CanActivateViaAuthGuard]},
{ path: 'admin', component: 'AdminComponent', canActivate: [CanActivateViaAuthGuard]},


As per your description you said this technically sets the boolean which will obviously get reset when user refreshes. The recommended way to maintain sign in state is to use Cookies or Session storage. For eg. after sign in you can add a key in session storage as

sessionStorage.setItem('isSignedIn', 1);

and retrieve it as

var state = sessionStorage.getItem('isSignedIn');

Answered By – Sumeet Kale

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.