1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Navigation to home page is not working from login page after logout method has been executed...

Discussão em 'Angular' iniciado por kumarp, Julho 3, 2025.

  1. kumarp

    kumarp Guest

    By default, Login page page opens if user is logged out. onLogin method works fine the first time and navigates to home page. On logout, it navigates back to login page. If I try again to login again without refreshing the page, navigation to home page does not work. Below is my sample code.

    app.route.ts

    export const routes: Routes = [
    {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full',
    },
    {
    path: 'login',
    component: LoginComponent,
    },
    {
    path: 'home',
    component: HomeComponent,
    canActivate: [authGuard],
    }];


    authGuard

    export const authGuard: CanActivateFn = (route, state) => {
    const router = inject(Router);
    const isLoggedIn = !!localStorage.getItem('loggedIn');
    if (isLoggedIn) return true;
    else {
    router.navigate(['/login']);
    return false;
    }


    };

    login.component.ts

    onLogin() {
    const { user, password } = this.loginForm.value;
    if (user.trim() === 'admin' && password.trim() === 'admin') {
    localStorage.setItem('loggedIn', 'true');
    this.router.navigate(['/home']);
    } else {
    alert(`Incorrect Username or password. Please try again.`);
    }
    }


    home.component.ts

    onLogout() {
    localStorage.removeItem('loggedIn');
    this.router.navigate(['/login']);
    }

    Continue reading...

Compartilhe esta Página