在 router.events 函数中导航到另一条路线会导致浏览器挂起

Navigate to another route within router.events function causes browser to hang up

我正在订阅顶部导航栏组件中的路由器事件:

this.router.events.subscribe(event => {
    if (event instanceof RoutesRecognized && this.authService.isLoggedIn()) {

         // some other custom if-logic then do this:
         this.router.navigate(['404']);
    }
});

当我执行上面的代码时,我的浏览器死机了,我不得不在任务管理器中关闭 chrome.exe...

为什么旧路线还在导航,却无法导航到另一条新路线?

我该怎么做?

您正处于重定向循环配合下。 您正在事件块内调用路由器导航方法,但您的条件中没有特定的 url。

目前您的代码将在 url 更新时执行,因此在每次重定向后它都会一次又一次地执行。

要解决这个问题,请尝试添加带有条件的路由,这样它就不会对每个 url 都执行,它会像

 this.router.events.subscribe(event => {
  let url = this.router.url;
  if (event instanceof RoutesRecognized && this.authService.isLoggedIn() && url !== "/404") {

     // some other custom if-logic then do this:
     this.router.navigate(['404']);
   }
  });

将 url 逻辑替换为您自己的逻辑,但您必须限制代码在特定页面上执行,而不是上面示例中的所有代码,它不会在 404 路由上执行。