Trying to get the following AuthGuard to properly redirect if a user is not logged in.
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
return authService.currentUser$.pipe(map((auth: User | null) => {
console.log(auth);
if(auth !== null){
console.log(auth);
return true;
}
return router.createUrlTree(['/login']);
}));
};
and in my AuthService file I utilize the following
private currentUserSource = new ReplaySubject<User | null>(1);
currentUser$ = this.currentUserSource.asObservable();
In my app.routes.ts file my Test component is being lazy loaded.
{path: 'test', loadComponent: () => import('./test/test.component').then(mod => mod.TestComponent), canActivate: [authGuard]},
Instead of redirecting the user to a login page, it just shows a blank page.
Thanks
I have re-written it several times utilizing different methods, but they all failed at redirecting.
New contributor
WorldDrknss is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.