Angular guard for checking if route has state
Asked Answered
S

2

6

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?

Selfhood answered 11/8, 2020 at 14:41 Comment(3)
Angular route objects an inconsistently nested. You might want to put some breakpoints on your return !!state.root.data to figure out when it gets hit and if you're looking in the right object for your state data.Anesthesia
Have you tried with single ! ?Oid
any data properties i find within route and state are empty as the transition happens, however the data is there when routing ends. what is single?Selfhood
D
5

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;
  } 
}
Ditchwater answered 28/1, 2021 at 15:29 Comment(0)
C
1

You can access the status like this:

@Injectable()
export default class RouteHasDataGuard implements CanActivate { 
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return !!window.history.state;
    } 
}
Centimeter answered 21/9, 2020 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.