路由器在导航启动事件内导航



我需要限制对某些页面的访问,如果用户尝试访问该页面,我需要将其重定向到主页。所以为此我有以下代码:

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

其中AllowedRoutes是一个数组,其中包含所有允许的路由 URL,如下所示:

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

当我使用this.router.navigate(['/']);时,它在控制台中显示一个错误,显示Maximum call stack size exceeded

如何解决此问题,或者是否有更好的方法仅允许某些 URL,而不是在每个路由中添加一个守卫来检查路由是否在数组中。

问题是您正在使用this.router.navigate(['/']);导航到/,这不是AllowedRoutes的元素。这将创建循环,因为每个导航到/都将重定向到/

对于全局RouteGuards,请查看此线程。

最新更新