1

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.

Maestro
  • 43
  • 1
  • 6

2 Answers2

1

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.

  • Thank you, it works! But I still don't understand, why the documentation refers, guard can return URLTree... It would make sense, if the URLTree made the application redirect, but it's not. Does not matter, if the guard returns true, or false, or URLTree, if you don't write the redirecting, the target will be loaded. – Maestro May 16 '23 at 11:14
  • I think if you create canactive guard then it can return url tree as well but you just created function returning true so guard is unaware what to do when it's false. Please upvote if it solves your problem, @Maestro – Nirav Ghodadra May 24 '23 at 11:02
  • Are you using a platform like Ionic? – Mike M May 31 '23 at 17:49
0

First of all you shouldn't subscribe inside guards. You can return the observable and it will be subscribed automatically.

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

    return authService.isLoggedIn().pipe(switchMap((isLoggedIn: boolean) => isLoggedIn ? of(true): router.navigateByUrl('/login')));
};
mhld
  • 163
  • 2
  • 9