问题
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?
回答1:
The value emitted by both observables is the same: !!authState
, but they shouldn't since one is supposed to emit true only when the user is authenticated, and the other is supposed to emit true only when the user is NOT authenticated.
map()
and tap()
do different things.
map()
tranforms the emitted event into something else.
tap()
produces a side effect and leaves the emitted event as is.
来源:https://stackoverflow.com/questions/57448349/guard-always-return-true