Angular - Guard doesn't redirect when logged in

Discussão em 'Angular' iniciado por Raphael, Agosto 19, 2025.

  1. Raphael

    Raphael Guest

    I'm developing an Angular (version 20) app that has the following guard:

    import { inject } from '@angular/core';
    import { CanActivateFn, Router } from '@angular/router';
    import { Store } from '@ngrx/store';
    import { map } from 'rxjs';

    import { AppState } from '../../../shared/store/app.state';

    import { selectFreelancer } from '../../../shared/store/freelancer/freelancer.selectors';

    export const unauthGuard: CanActivateFn = (route, state) => {
    const store = inject(Store<AppState>);
    const router = inject(Router);

    return store.select(selectFreelancer).pipe(
    map((freelancer) => {
    if (freelancer === null) {
    return true;
    }

    router.navigate(['/']);
    return false;
    }),
    );
    };


    I added it here to my app.routes.ts:

    import { Routes } from '@angular/router';

    import { unauthGuard } from './core/guards/unauth/unauth-guard';

    export const routes: Routes = [
    {
    path: 'auth',
    loadChildren: () =>
    import('./modules/auth/auth-module').then((m) => m.AuthModule),
    canActivate: [unauthGuard],
    },
    {
    path: '',
    loadChildren: () =>
    import('./modules/home/home-module').then((m) => m.HomeModule),
    },
    {
    path: '**',
    redirectTo: '/auth/login',
    },
    ];


    When freelancer === null, I should be able to navigate to the route; when it is not null, I should be redirected to /. Now, when I'm logged out it works properly: I can navigate to everything that starts with /auth. However, when I'm logged in, I should not be able to navigate to a route that starts with /auth, but I can. How can I deactivate /auth/* when I'm logged in?

    Continue reading...

Compartilhe esta Página