0

I need to restrict access to some pages and if the user tries to access the page, I need it to be redirected to home page. So for this I have the following code :

this.router
    .events
    .subscribe(
        (event) => {
            if (event instanceof NavigationStart) {
                if (!AllowedRoutes.includes(event.url)) {
                    this.router.navigate(['/']);
                }
            }
        }
    );

Where AllowedRoutes is an array with all the allowed route urls like the following:

export const AllowedRoutes: any = [
    '/allowed-route-one',
    '/allowed-route-two',
    '/allowed-route-three'
];

When I use this.router.navigate(['/']); it is showing an error in console that says Maximum call stack size exceeded

How can this be fixed or is there any better way to allow some URLs only instead of adding a guard in every route to check if the route is in the array.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Happy Coder
  • 4,255
  • 13
  • 75
  • 152

1 Answers1

1

The problem is that you're navigating to / with this.router.navigate(['/']); which is not an element of AllowedRoutes. This creates the loop, because every navigation to / is gonna be redirected to /.

For global RouteGuards, have a look at this thread.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195