0

I've created a Guard that prevent a user to manually access an URL and it's working fine.

The problem is that when I refresh the page, the Guard redirects me.

Here's the code:

export class NavigationGuard implements CanActivate {

  constructor(private router: Router) { }

  canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.router.navigated) {
      return true
    } else {
      this.router.navigate(['/'])
      return false
    }
  }
  
}

I've seen that I can use the following code to get a refresh event but it's basically the opposite of this.router.navigated so it's not working.

this.subscription = router.events.subscribe((event) => {
        if (event instanceof NavigationStart) {
          browserRefresh = !router.navigated;
        }
    });

Is it possible that have those 2 behaviours working at the same time in my Guard ?

PepeW
  • 477
  • 1
  • 8
  • 24
  • On 'refresh', `this.router.navigated` will be false because you haven't navigated anywhere via the router. If you want this to not redirect you to '/', you'll need to key off of something other than `this.router.navigated` in your if. – Roddy of the Frozen Peas Oct 19 '21 at 22:19

1 Answers1

0

Maybe you can use the logic of "is this page refreshed" with a combination with the this.router.navigated to check that the page can be access within the angular app.

Something like this:

    const pageAccessedByReload = (
      (window.performance.navigation && window.performance.navigation.type === 1) ||
        window.performance
          .getEntriesByType('navigation')
          .map((nav: any) => nav.type)
          .includes('reload')
    );
    return this.router.navigated || pageAccessedByReload
Alejandro Barone
  • 1,743
  • 2
  • 13
  • 24