2

I want to craete angular route guard in my app. I found this code but don't understand why we map user to !!user. What's the purpose of map(user => !!user) line?

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> {

      return this.auth.user.pipe()
           take(1),
           map(user => !!user),
           tap(loggedIn => {
             if (!loggedIn) {
               console.log('access denied')
               this.router.navigate(['/login']);
             }
         })
    )
Staxxx6
  • 95
  • 5
  • actualy in this case you can also use something like this `map(Boolean)` works the same way buts even shorter – Xesenix Jun 19 '19 at 20:14

1 Answers1

3

!! is a common way to cast something to a boolean.

By applying the NOT operator (!) twice in the map() function, it maps the user to a boolean which is then used as loggedIn which is used in the tap() function.

Likely the user is supposed to be an object with userdata (which has a truthy value).

I also assume that if you are not logged in, the user will be null or undefined (which has a falsy value).

Daniel
  • 10,641
  • 12
  • 47
  • 85