Reputation: 981
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.
Upvotes: 0
Views: 657
Reputation: 6432
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);
}
}
Upvotes: 2