angulartypescriptguardangular-router-guards

Router doesn't redirect by guard


I have an angular app with Angular 15. App-routing module somehow doesn't redirect, when a guard returns the UrlTree. app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { LoggedInGuard } from './guard/logged-in.guard';

import { HomeComponent } from './component/home-component/home.component';
import { LoginComponent } from './component/login-component/login.component';

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

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

LoggedInGuard is defined and sends a POST request, and then gets the response, it's false, I console-logged it. logged-in.guard.ts

import { inject } from '@angular/core';
import { Router, UrlTree } from '@angular/router';

import { AuthService } from '../service/auth.service';

export const LoggedInGuard = () => {
    const authService = inject(AuthService);
    const router = inject(Router);

    authService.isLoggedIn().subscribe(isLoggedIn => {
        console.log(isLoggedIn);
        if (isLoggedIn) {
            return true;
        }
        return router.parseUrl('/login');
    });
};

The console log writes false, but I'm still redirected to the home path and stay there. Console doesn't write any error. I made that based on the Angular documentation, but didn't find anything. They wrote, the guard has to return boolean or UrlTree... but it won't redirect.


Solution

  • I think you should try like this

      if (isLoggedIn) {
            return true;
      }
      this.router.navigate(['login']);
      return false;
    

    If it still doesn't work do lemme know.