To prevent users from returning to the login page, you can implement guards using CanActivate.
import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CanActivateAuthGuard implements CanActivate {
constructor(private router: Router) {
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (sessionStorage.getItem('user') !== null && localStorage.getItem('token')) {
console.log('A logged-in user is trying to re-login');
this.router.navigateByUrl('/home');
return false;
}
return true;
}
}
In your routing module, add the following:
{ path: 'loginpage',
loadChildren: () => import('./features/auth/auth.module').then(m => m.AuthModule),
canActivate: [CanActivateAuthGuard]
},