【问题标题】:Angular guard with multiple conditions and redirects具有多个条件和重定向的 Angular 防护
【发布时间】:2019-02-04 16:02:23
【问题描述】:

我想创建一个复杂的路由器保护来检查用户是否在 Web 应用程序中进行了身份验证,如果是,它还会检查其他条件,并且对于每个真实条件,它都会重定向到一个页面(但是在同一个路由器下)警卫)。为了更好地在路由器保护中解释这一点,我必须这样做:

canActivate(state: RouterStateSnapshot) {
   if(isAuthenticated()) {
     if(!isEmailVerified) {
        // redirect to the "check the email" page
     }
     else if(!isProfileComplete()) {
        // redirect to profile completion page
     }
     else {
        // redirect to user homepage
     }
    return true;
   } else {
   // redirect login
   return false;
   }
}

问题实际上是这不起作用,因为每个重定向都会带到受此保护保护的页面,然后每个重定向都会调用另一个重定向并以无限循环结束。如果 state.url 与我们重定向到条件主体内部的不同,我已经尝试检查条件内部,但这不起作用。有没有简单的解决方案来做到这一点?

【问题讨论】:

  • 在重定向之前返回true。
  • 如果函数已经返回,如何重定向?
  • 我认为你在滥用警卫。为什么不在组件上使用 if 条件?你可以让一个组件/组件在 isEmailVerified 时显示,另一个在 isProfileComplete 时显示等...易于调试易于测试
  • 问题是我只想把登录放在守卫中。否则我应该在多个组件中进行多次检查,这不容易调试。此外,如果用户编写例如个人资料完成页面 url 如果个人资料已经完成,我不希望他去那里,这就是为什么该路线也受到保护

标签: angular angular-routing angular7 angular-router-guards angular-guards


【解决方案1】:

我建议为每个条件使用重定向字符串,并在函数末尾重定向守卫,例如;

canActivate(state: RouterStateSnapshot) {
   let redirectionPath: string = "";
   if(isAuthenticated()) 
   {
        if(!isEmailVerified) {
           redirectionPath = "emailverified";
        }
        else if(!isProfileComplete()) {
        // redirect to profile completion page
           redirectionPath = "completionPage";
        }
        else {
          // redirect to user homepage
           redirectionPath = "homepage";
        }
   } else {
           redirectionPath = "login";
   }

   this.router.navigate(['/your-path']);
   return true;
} 

【讨论】:

  • 我认为这是一种更好的重定向方法,但循环问题仍然存在......
  • @GiovanniBertoncelli 您能否提供一个具有相同行为的简单 stackblitz 来查看确切的问题?
【解决方案2】:

if(!isEmailVerified) {
        // redirect to the "check the email" page
     }
     else if(!isProfileComplete()) {
        // redirect to profile completion page
     }
     else {
        // redirect to user homepage
     }

从守卫中删除此代码并将其添加到另一个守卫(重定向守卫)中,您可以在其中使用条件重定向页面

【讨论】:

  • 谢谢!但是我可以将条件redirectTo放在路由模块中吗?
猜你喜欢
  • 2017-07-01
  • 2011-06-17
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 2021-10-16
  • 2021-02-25
  • 2012-01-23
  • 1970-01-01
相关资源
最近更新 更多