Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write condition in route in angular / ionic

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

like image 602
Abd Abughazaleh Avatar asked Mar 03 '23 01:03

Abd Abughazaleh


1 Answers

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']);
}
like image 161
Wellington Júnior Avatar answered Mar 04 '23 15:03

Wellington Júnior