Reputation: 6348
I am attempting to use the canActivate feature on my app routing, however whenever I compile the app the log shows constantly refreshing with fail messages that I had console.log()'d out for visibility.
Is there something I am missing here?
Upvotes: 2
Views: 740
Reputation: 34693
You are redirecting to the wrong route in your canActivate
method. Redirect to login
. Here are the change you need to make:
// if not logged in, navigate to login screen
this.router.navigate(['login'], {queryParams: {returnUrl: state.url}});
When you are redirecting to ''
, it goes again to the canActivate
guard, hence the infinite loop.
Upvotes: 2
Reputation: 4039
You are navigating to root by this.router.navigate([''], {queryParams: {returnUrl: state.url}});
which causes the guard to kick in again therefore it gets in the loop.
Try this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
Upvotes: 1
Reputation: 4471
this.router.navigate([''], {queryParams: {returnUrl: state.url}});
will get executed everytime when not logged in, thus causing your infinite redirects as in your router config
{path: '', component: HomepageComponent, canActivate: [AuthGuard]},
Add an explicitly path for an e.g. LoginComponent.
And {path: '**', redirectTo: ''}
should also point to some kind of CatchUnmatchedPathComponent where a User gets some kind of 404 page represented.
Upvotes: 3