守卫总是返回真 [英] Guard always return true

查看:35
本文介绍了守卫总是返回真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 angular 应用中有两个非常相似的守卫.首先检查用户登录:

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)
      )
  }
}

区别仅在于: !auth ?this.router.navigate(['/']) vs auth ?this.router.navigate(['/']).

The difference only is: !auth ? this.router.navigate(['/']) vs 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?

推荐答案

两个 observable 发出的值是相同的:!!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() and tap() do different things.

map() 将发出的事件转换为其他内容.

map() tranforms the emitted event into something else.

tap() 产生副作用并保持发出的事件不变.

tap() produces a side effect and leaves the emitted event as is.

这篇关于守卫总是返回真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆