I have two pretty similar guards in angular app. First of them checking is User logged in:
// isUser guard
export class isUser implements CanActivate {
constructor(
private fireAuth: AngularFireAuth,
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.fireAuth.authState.pipe(
take(1),
map(authState => !!authState),
tap(auth => !auth ? this.router.navigate(['/']) : true)
)
}
}
And this one work properly: when user is not logged in it's not allow him to open protected page.
The next guard is almost the same, but it check if user in not logged in:
export class isGuest implements CanActivate {
constructor(
private fireAuth: AngularFireAuth,
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.fireAuth.authState.pipe(
take(1),
map(authState => !!authState),
tap(auth => auth ? this.router.navigate(['/']) : true)
)
}
}
The difference only is: !auth ? this.router.navigate(['/'])
vs auth ? this.router.navigate(['/'])
.
But isUser
guard work good, and isGuest
always allow page for user.
What I did wrong, and why it's can not work?