Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular Auth Guard – users can access the login page only when they are not logged in and can access other pages only when they are logged in

Auth Guard


    export const AuthGuard: CanActivateFn = (
            route: ActivatedRouteSnapshot,
            state: RouterStateSnapshot,
          ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree => {
            const router = inject(Router);
            if (localStorage.getItem('userdata')) {
              return true;
            } else {
              return router.navigate(['login']);
              /** no need to return 'false', just return the promise */
            }
          };

I want users to access the login page only when they are not logged in and other pages only when they are logged in.

If in localstorage there is no data, then it can access the login page, and if localstorage has data, then it can access the dashboard. In the above code, if localstorage has data, then not only does it give access to the dashboard page, but it also gives access to the login page.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If local storage has no data, then only give access to the login page that I want.
"What am I doing wrong?

>Solution :

Is this what you need?

AuthGuard:

export const authGuard: CanActivateFn = () => {
  return !!localStorage.getItem('userdata') || inject(Router).navigate(['login']);
};

PublicGuard:

export const publicGuard: CanActivateFn = () => {
  return !localStorage.getItem('userdata') || inject(Router).navigate(['dasboard']);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading