I am trying to use seperate guards for seperate pages. I'm basically checking a bool parameter to understand if there's an user logged or not.
these are my two guard.ts codes
export class IsAuthenticatedGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router){}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.isLoggedIn$.pipe(
tap(isLoggedIn => {
if(!isLoggedIn){
//redirect
this.router.navigate(['login']);
}
})
);
}
}
export class LoginPageGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router){}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.isLoggedIn$.pipe(
tap(isLoggedIn => {
if(isLoggedIn){
//redirect
this.router.navigate(['overview-page']);
}
})
);
}
}
and this is the code where I use guards (app.module.ts) I deleted pages between overview-page and login since they're not related.
HttpClientModule,
RouterModule.forRoot([
//{path: '', component: UserTargetsComponent },
//{path: '', component: NavbarComponent },
{path: '', component: OverviewPageComponent, canActivate: [IsAuthenticatedGuard]},
{path: 'overview-page', component: OverviewPageComponent, canActivate:[IsAuthenticatedGuard]},
{path: 'login', component: LoginComponent, canActivate: [LoginPageGuard]},
{path: '**', component: NotFoundComponent, canActivate: [IsAuthenticatedGuard]}
])
For a brief time, it worked as I expected. If user is logged in it doesn't allow to go to login page, directs you to overview page and if user is not logged in, vice versa.
Now it just doesn't respond. just goes to main page (localhost:xxx/) when I go to login page by typing on browser bar. Same on overview-page. After few tries, pages usually crashes so I restart the angular app.
If I stop using canActivate on login page, everything works fine. when I put it back breaks again. I guess that's somehow causing this problem but how?
Any ideas? Probably I'm missing something small.
CodePudding user response:
Thats probably because your LoginPageGuard
returns false if user is not logged in. So then it prevents the 'Login' route from being loaded, so where are they supposed to go? LoginPageGuard
should return true if they are unauthenticated and false if they are with the re-route
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.isLoggedIn$.pipe(
map(isLoggedIn => {
if(isLoggedIn){
//redirect
this.router.navigate(['overview-page']);
// if they are authenticated do not allow them to load login
return false;
}
// if they are NOT authenticated, allow them to load this route
return true;
})
);