Angular guard for checking if route has state

Viewed 1468

I have a component to which navigate like this

this.router.navigate(['results'], { state });

and once there i grab the data in the contructor

constructor(private router: Router) { 
  const { state } = this.router.getCurrentNavigation().extras;
}

i want to place a guard to check for the existense of this data, otherwise navigate elsewhere

@Injectable()
export default class RouteHasDataGuard implements CanActivate { 
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return !!state.root.data;
    } 
}

but this isnt working. can you help me with this?

2 Answers

Do not read extras in guard constructor. Read extras in canActivate() method.

@Injectable()
export default class RouteHasDataGuard implements CanActivate { 

  constructor(private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const { state } = this.router.getCurrentNavigation().extras;
    return !!state.root.data;
  } 
}

You can access the status like this:

@Injectable()
export default class RouteHasDataGuard implements CanActivate { 
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return !!window.history.state;
    } 
}
Related