as title says I'm stuck in loop as I was working with routing and guards. My plan was activate LogedInGuard if user il logged in, so that he cannot see login form if token exists. If I go on that route, console.log is saying "logedin guard return false" all over again. Here's my routing code:
{
path: 'admin',
component: AdminComponent,
canActivate: [LogedInGuard],
children: [
{ path: '',
component: AdminLoginComponent,
pathMatch: 'full',
canActivate: [LogedInGuard],
},
{
path: 'dashboard',
canActivate: [AuthGuard],
component: AdminDashboardComponent,
children: [
{ path: '', component: AdminNewsListComponent},
{ path: 'add-news/:id', component: AdminAddNewsComponent},
{ path: 'add-news', component: AdminAddNewsComponent},
]
}
]
},
and guard code:
@Injectable()
export class LogedInGuard implements CanActivate {
constructor(private auth: AdminService, private router: Router) {}
canActivate(){
if(this.auth.isAuthenticated()){
console.log("logedin guard return false");
this.router.navigate(['/admin/dashboard'])
return false;
}
console.log("logedin guard return true");
return true;
}
}
CodePudding user response:
Well, you have a loop because once you navigate to any path starting with /admin
your LogedInGuard
is called. In this guard you navigate to a route starting with /admin
, which will result in another call to LogedInGuard
.
In order to prevent getting stuck in a loop you should remove LogedInGuard
from your parent route config (for /admin
):
{
path: 'admin',
component: AdminComponent,
children: [
{ path: '',
component: AdminLoginComponent,
pathMatch: 'full',
canActivate: [LogedInGuard],
},
{
path: 'dashboard',
canActivate: [AuthGuard],
component: AdminDashboardComponent,
children: [
{ path: '', component: AdminNewsListComponent},
{ path: 'add-news/:id', component: AdminAddNewsComponent},
{ path: 'add-news', component: AdminAddNewsComponent},
]
}
]
},