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?

  • 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. – mwilson Aug 11 '20 at 15:03
  • Have you tried with single ! ? – Vega Aug 12 '20 at 02:05
  • 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? – Konstantinos Papakonstantinou Aug 12 '20 at 07:29

2 Answers2

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;
  } 
}
Michal.S
  • 501
  • 6
  • 12
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;
    } 
}
intropedro
  • 2,804
  • 1
  • 24
  • 25