My angular app running Angular 15 is facing an issue with the App-routing module not redirecting 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 { }
The LoggedInGuard sends a POST request and upon receiving a false response, 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');
});
};
Even though the console logs false, I am still being redirected to the home path and remaining there without any errors in the console. I have followed the Angular documentation which states that the guard should return boolean or UrlTree, but it does not seem to be redirecting as expected.