qqilihq
qqilihq

Reputation: 11454

Angular Guards: Prevent manually accessing a URL

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)

Upvotes: 4

Views: 3477

Answers (1)

Steve
Steve

Reputation: 602

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';

Upvotes: 2

Related Questions