0

I have an auth class set up like this:

export class AuthService {
  user = new Subject<string>();

  login(name: string) {
    this.user.next(name);
  }

}

I have an auth guard set up to check to see if my user subject has a value like this:

export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    return this.authService.user
      .pipe(
        map(user => {
          const isAuth = !!user;
          if (isAuth) {
            return true;
          }
          return this.router.createUrlTree(['/login']);
        })
      );
  }
}

I put print statements in the return and they never get called. The page never loads and it never re-directs either. If I just return true or false it works but by returning my authService.user nothing seems to happen.

Rafi Henig
  • 5,950
  • 2
  • 16
  • 36
Martheli
  • 931
  • 1
  • 16
  • 35

1 Answers1

2

The apparently issue with your currently code is that no part of your app is pushing any data into user subject when subscribing to it in your guard.

How about using BehaviorSubect so that when ever you subscribe to it you'll accept a value? using BehaviorSubect unless you push into it a new value you'll accept the initial value right away when subscribing to it.

export class AuthService {
   user = new BehaviorSubject<string>(null);

   login(name: string) {
     this.user.next(name);
   }
}
Rafi Henig
  • 5,950
  • 2
  • 16
  • 36
  • I am subscribing and reading this value on another component without any issue so the Subject is being populated correctly. – Martheli Nov 14 '19 at 02:00
  • What do you get in map when debugging? – Rafi Henig Nov 14 '19 at 02:04
  • If I add a console log in the map it never gets called. – Martheli Nov 14 '19 at 02:06
  • Try BehaviorSubect, as it contains the old value in it as opposed to a regular subject where you only get the value if you were subscribed to it when it's been sent the new value. – Rafi Henig Nov 14 '19 at 02:08
  • I agree, try BehaviorSubject or ReplaySubject. Subject will only emit NEW values, but if you subscribe to it it will NOT emit any existing values – Damian C Nov 14 '19 at 02:10