Angular Guard具有多个条件和重定向

时间:2019-02-01 10:47:36

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

我想创建一个复杂的路由器防护,检查用户是否在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是否与我们重定向到条件主体内部的状态不同,但这不起作用。有一个简单的解决方案吗?

2 个答案:

答案 0 :(得分: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;
} 

答案 1 :(得分:0)

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

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