Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Async Router Guards

Tags:

angular

We have a Router Guard which checks if a user is logged in and admin It should also check if a request we send to a server is has the right result.

The problem is the canActivate function is finished before the server request is finished, so the Router Guard is always false.

I hope you have a solution for this problem

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    var user = JSON.parse(localStorage.getItem('currentUser'));
    if (user != null&&!user.isNotAdmin) {
      if(this.userService.isLoggedIn(user)){
          return true;
      }else{
          return false;
      }
    }else{

    // not logged in so redirect to login page with the return url
    this.router.navigate([''], { queryParams: { returnUrl: state.url } });
    return false;
    }
like image 786
Jakob Kreinecker Avatar asked Mar 06 '18 12:03

Jakob Kreinecker


1 Answers

You have to use async/await to ensure canActivate waits till the resolution of your server request. Here's some sample code to help you:

/* UserService */
isLoggedIn(user): Observable<boolean> {
  // check if user is logged in
  return isUserLoggedIn;
}

/* Guard */
async canActivate(route: ActivatedRouteSnapshot, 
  state: RouterStateSnapshot): Promise<boolean> {
const user = JSON.parse(localStorage.getItem('currentUser'));
if (user !== null && !user.isNotAdmin) {

  const isUserLoggedIn: boolean = await this.userService.isLoggedIn(user).toPromise();
  // toPromise() converts Observable to Promise (async/await only works on Promises)
  // the code 'waits' at the above line till the server request is resolved

  return isUserLoggedIn;

} else {
  // not logged in so redirect to login page with the return url
  this.router.navigate([''], { queryParams: { returnUrl: state.url } });
    return false;
}

References if you want to read further:

  • async/await documentation
  • es6 key guidelines
like image 117
aryaag Avatar answered Sep 17 '22 13:09

aryaag