2

so I am using a simple authguard to redirect me to the login page when there's no session, but it only works when I refresh the page!

my routing module:

const routes: Routes = [
  { path: '', component: HomeComponent, canActivate: [AuthGuardService] },
  { path: 'login', component: LoginComponent },
  { path: 'logout', component: LogoutComponent, canActivate: [AuthGuardService] }
];

my authguard:

export class AuthGuardService implements CanActivate {
  constructor(private router: Router,
    private authService: AuthenticationService) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authService.isUserLoggedIn())
      return true;

    this.router.navigate(['login']);
    return false;

  }
}
Basel Issmail
  • 3,847
  • 7
  • 20
  • 36
Amine Maalfi
  • 145
  • 9
  • 1
    Do you get any error in the console? – Nicholas K Aug 14 '19 at 17:58
  • 2
    What does your `this.authService.isUserLoggedIn()` actually do? – Ajmal Aug 14 '19 at 17:59
  • i get an error if there's an http request in the page of course! but nothing related to the guard and, @AjmalAli isUserLoggedIn() checks if the session has a username stored in it, and the constructor of the service in which it is placed, sends a request to the back-end and checks if there's still a session if there's none, it clears the sessionStrorage! – Amine Maalfi Aug 14 '19 at 18:44
  • I think, You may also want to implement canActivateChild interface too. See the difference explained in [this](https://stackoverflow.com/a/40284274/9958058). HTH – Nirav Aug 14 '19 at 18:50
  • i believe this is used when you have child routes like /book/:id , /book/:id/details etc... but it's not my case – Amine Maalfi Aug 14 '19 at 18:57
  • is isUserLoggedIn() an async function? – Bill Cheng Aug 14 '19 at 21:14

0 Answers0