I'm using ionic 5 framework to build an application , I want to add condition in route if user already signed in before change route .
app-routing.module.ts file :
const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
loadChildren: './home/home.module#HomePageModule'
},
{
path: 'doctors',
loadChildren: () => import('./doctors/doctors.module').then(m => m.DoctorsPageModule)
},
{
path: 'dashboard',
loadChildren: () => import('./user/dashboard/dashboard.module').then(m => m.DashboardPageModule),
canLoad: [AuthGuard],
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules})
],
exports: [RouterModule]
})
export class AppRoutingModule {
}
I want to add condition here :
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
if user already signed change redirectTo: 'home'
to be redirectTo: 'dashboard'
how can i do this ?
Note : I'm used
AuthGuard
to prevent user from signed into some routs
You must use your AuthGuard, but the canActivate function, like this:
Routes:
{
path: 'dashboard',
loadChildren: () => import('./user/dashboard/dashboard.module').then(m => m.DashboardPageModule),
canLoad: [AuthGuard],
canActivate: [AuthGuard]
},
AuthGuard
constructor(private router:Router) {}
canLoad = () => {//...your code }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (!isLoggedIn()) { //your verification to logged In
this.router.navigate(['/']);
return false;
}
return true;
}
Finally, in your HomeComponent, you redirect in case if loggedIn.
HomeComponent.ts
ngOnInit(): void {
if(isLoggedIn()) this.router.navigate(['dashboard']);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With