Answer the question
In order to leave comments, you need to log in
How guard should work with Observable?
user$ - Observable can be either null or a user object. Depending on this, he should start up on the page or display an error in the console, how to handle this correctly?
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> {
return this.authService.user$.pipe(
map( user => !!user)
);
}
Answer the question
In order to leave comments, you need to log in
Maybe it's better to save user data or an authorization token in localstorage, and check for its presence?
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const token = this.authService.getAuthorizationToken();
if (token) {
return true;
}
// not logged in so redirect to sign-in page with the return url
this.router.navigate(['/account/sign-in'], { queryParams: { returnUrl: state.url }});
return false;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question