In my application when a user try to see the page "home" he is redirected to the login page (if he's not already logged in). If the user is already logged in, or after he logged in, I want to redirect him to the page "home" or whatever page he was trying to see before being redirected to login.
This is my canActivate module. Instead of returning true, how can I redirect the user to page he came from? Is it possibile to do it inside the canActivate method?
export class RouteGuardService implements CanActivate{
constructor(private router:Router, private authService:AuthService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
return this.authService.user.pipe(
take(1),
map(user=>{
if(user && user.token){
return true;
}
return this.router.createUrlTree(["/login"]);
})
);
}
}
CanActivate guards a link and allow to access conditionally such as in user authentication application. links will be guarded by CanActivate and will be accessible only after login.
So in your code you just need to remove one line
Final Solution:
in routing file:
In AuthServiceFile once the user is succefully logged in :