简体   繁体   English

router.navigate无法在Angular中运行或进入无限循环

[英]router.navigate not working in Angular or going into infinite loop

I'm using Angular 6. I have a service called UserService which is calling a function called getUser() . 我正在使用Angular6。我有一个名为UserService的服务,该服务正在调用名为getUser()的函数。

In the function I want to navigate to the login page when the user has an invalid token. 在功能中,当用户拥有无效令牌时,我想导航至登录页面。

getUser(){
 this.user = JSON.parse(sessionStorage.getItem('currentUser'));
 if (!this.user) {
   this.router.navigate(['login']);
   this.toastr.error('Unknown Logged In User');
   return false;
 }
 this.token = this.user.token;
 return this.user;
}

I'm calling getUser in a lot of components. 我在很多组件中都调用getUser。 for example in the ActiveOrdersComponent 例如在ActiveOrdersComponent

getCurrentUser() {
    let loggedUser = this.userService.getUser();
    if (loggedUser) {
        this.info = {
            currentUser: {
                currentUserName: loggedUser.first_name + ' ' + loggedUser.last_name
            }
        }
    }
    return this.info.currentUser;
}

Im using LazyLoader. 我正在使用LazyLoader。

My original path is '/auth/orders/active' 我的原始路径是'/auth/orders/active'

Destination Login path is '/login' 目标登录路径为'/login'

the function getUser() is not navigating and going into an infinite loop. 函数getUser()无法导航并进入无限循环。 and the browser is freezing with multiple console errors. 并且浏览器因多个控制台错误而冻结。

the function is returning false and continues to execute the code in the component (which will break because I'm returning false). 该函数返回false,并继续执行组件中的代码(由于我返回false,所以代码将中断)。

i have had this issue before and after some hours i could find the problem. 我在几个小时前后都遇到了这个问题,我可以找到问题。 there are 2 things happen when you face with this problem: 遇到此问题时,会发生两件事:

  1. when you want to redirect user to another page and use navigate method, you should put the address like this : 当您要将用户重定向到另一个页面并使用Navigation方法时,您应该输入如下地址:

      this.router.navigate(['/login'] 
  2. sometimes you write this code in its own component. 有时您会在自己的组件中编写此代码。 for example, you write the code above in the login component. 例如,您在登录组件中编写了上面的代码。 this causes that you face with infinite loop when you refreshing the page. 这会导致刷新页面时面临无限循环。 just you should change the address in navigate method to put away this problem. 只是您应该在Navigation方法中更改地址以解决此问题。

i hope that it helps you 我希望它可以帮助您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM