Guard always return true

空扰寡人 提交于 2019-12-12 07:03:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!