Angular Auth Guard - users can access the login page only when they are not logged in and can...

Discussão em 'Angular' iniciado por user23247200, Janeiro 9, 2025.

  1. user23247200

    user23247200 Guest

    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.

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

    Continue reading...

Compartilhe esta Página