4

We have several routes in our app which are not supposed to be navigated by the user by directly entering their URLs into the browser’s address bar.

Instead we only want to make them accessible when we programmatically navigate using router.navigate() through our application logic.

Using Angular’s CanActivate guard, is there some flag or attribute which we could use to distinguish between those two cases:

  1. Route is being accessed directly as the user typed /no/direct/access into the address bar

  2. Route is being accessed via router.navigate(['/', 'no', 'direct', 'access']) (which might in turn be triggered by a different guard, so router.navigated unfortunately doesn’t seem to help here)

qqilihq
  • 10,794
  • 7
  • 48
  • 89

1 Answers1

2

I didn't found possibility to distinguish between cases you've described. I found a way to prevent manual navigation to route though

You can check .navigated property on router. Accordingly to docs it is

True if at least one navigation event has occurred, false otherwise

export class PreventDirectNavigationGuard implements CanActivate {
  constructor(
    private _router: Router,
  ) { }
  canActivate(
    _activatedRouteSnapshot: ActivatedRouteSnapshot,
    _routerStateSnapshot: RouterStateSnapshot,
  ): boolean | UrlTree {

    return this._router.navigated;
  }
}

Also Angular has navigation trigger flag. From source code

Identifies how this navigation was triggered.

imperative - Triggered by `router.navigateByUrl` or `router.navigate`.
popstate -  Triggered by a popstate event.
hashchange - Triggered by a hashchange event.
       trigger: 'imperative' | 'popstate' | 'hashchange';
Steve
  • 582
  • 3
  • 6
  • If you manipulate URL your app will be reloaded,and it will be considered as first navigation for angular – Steve Nov 08 '19 at 14:02
  • Thanks for this. Unfortunately, `router.navigated` is `false` when being redirected from another guard (see point 2 in my question), as there was no “navigation” before :-( Realize that this is an edge-edge case and I’ll probably need to overthink this entirely. – qqilihq Nov 08 '19 at 16:48