K
K
Keppp2020-04-29 15:20:12
Angular
Keppp, 2020-04-29 15:20:12

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

1 answer(s)
S
Sergei Iamskoi, 2020-04-29
@syamskoy

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;
  }

You can consider the situation if the user himself fills these fields with fake data in the local store and goes to a closed page. Then nothing terrible will happen, because. the departed request to receive data on this page will receive a 401 error from the backend (the token is fake), which means that the handler-error overwrites the localstorage and throws the user out for authorization. Those. this way is pretty safe.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question