Reputation: 5535
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
Upvotes: 4
Views: 3277
Reputation: 332
The auth guard is an angular route guard that's used to prevent unauthenticated or unauthorized users from accessing restricted routes, it does this by implementing the CanActivate interface which allows the guard to decide if a route can be activated with the canActivate() method. If the method returns true the route is activated (allowed to proceed), otherwise if the method returns false the route is blocked.
The auth guard uses the authentication service to check if the user is logged in, if they are logged in it checks if their role is authorized to access the requested route. If they are logged in and authorized the canActivate() method returns true, otherwise it returns false and redirects the user to the login page.
Angular route guards are attached to routes in the router config, this auth guard is used in app.routing.ts to protect the home page and admin page routes.
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '@app/_services';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthenticationService
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser) {
// check if route is restricted by role
if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
// role not authorised so redirect to home page
this.router.navigate(['/']);
return false;
}
// authorised so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
Upvotes: 2
Reputation: 612
You can use a resolver to solve this problem like TestResolverService
:
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, Router } from '@angular/router';
import { AuthService } from '@core/services/auth/auth.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class TestResolverService implements Resolve<any> {
constructor(private router: Router, public authService: AuthService) {}
resolve(route: ActivatedRouteSnapshot): Observable<any> | Promise<any> | any {
// or anyhow you specify if user is signed in or not
return this.authService.subjectUser.pipe(
map((user) => {
const isAuth = !!user;
if (isAuth) {
this.router.navigate(['/dashboard']);
} else {
this.router.navigate(['/home']);
return false;
}
})
);
}
}
And in your routerModule:
{ path: '', resolve: { TestResolverService }, children: [] },
{
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],
},
Upvotes: 2
Reputation: 673
/***** gaurd */
@Injectable()
export class checkLogged {
canActivate() {
//check user is logged in
}
}
const routes: Routes = [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full',
canActivate: [checkLogged]
},
{
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 {
}
Upvotes: 2
Reputation: 279
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']);
}
Upvotes: 2