守卫永远返回true [英] Guard always return true
问题描述
我在角度应用程序中有两个非常相似的后卫.首先检查的是用户登录:
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.
下一个防护措施几乎相同,但是它检查 not 中的用户是否登录:
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)
)
}
}
区别仅在于:!auth ? this.router.navigate(['/'])
与auth ? this.router.navigate(['/'])
.
但是isUser
防护效果很好,并且isGuest
始终允许用户使用页面.
我做错了什么,为什么它不起作用?
But isUser
guard work good, and isGuest
always allow page for user.
What I did wrong, and why it's can not work?
推荐答案
两个可观察对象发出的值是相同的:!!authState
,但是它们不应该这样,因为仅当用户通过身份验证时,它们才应该发出true,另一个应该仅在用户未通过身份验证时才发出true.
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()
和tap()
做不同的事情.
map()
将发出的事件转换为其他事件.
map()
tranforms the emitted event into something else.
tap()
会产生副作用,并保持发出的事件不变.
tap()
produces a side effect and leaves the emitted event as is.
这篇关于守卫永远返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!