0

Im trying to make a custom Guard for my landing page on Angular with Auth0, the logic is this:

User types http://localhost:4200

  • If user is logged in then should redirecto to htttp://localhost:4200/dashboard
  • If user is not logeed in then should let me follow htttp:://localhost:4200
export class LandingPageGuard implements CanActivate {
  constructor (private authService: AuthService, private router: Router) {}

  canActivate (
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean | UrlTree> | boolean {
    return this.authService.isAuthenticated$.pipe(
      tap(loggedIn => {
        if (loggedIn) {
          this.router.navigate(['dashboard']) // Continue to dashboard
        } else {
          // Continue to landing page
        }
      })
    )
  }
}
{
  path: '',
  canActivate: [LandingPageGuard ],
  loadChildren: () =>
    import('src/app/modules/landing-page/landing-page.module').then((m) => m.LandingPageModule)
}

I dont know why this doesnt work and why I can't return a value (true or false) inside tap method that responds canActivate

Note: Others Routes use default AuthGuard from @auth0/auth0-angular

  • 1
    Because `tap` applies a function whose result is discarded. It's purpose is to perform a side effect and not to transform the observable. Instead use `map` or `flatMap`. `this.authService.isAuthenticated$.pipe(flatMap(loggedIn => loggedIn? this.router.navigate(['dashboard']) : return of(false)) ` – Aluan Haddad May 22 '23 at 03:21

0 Answers0