【问题标题】:Working with multiple guards on a route file在路由文件上使用多个警卫
【发布时间】:2020-02-18 01:05:39
【问题描述】:

拜托,我的路线有些问题。 当应用程序启动时(http://localhost:4200),它的默认是进入登录页面,并在成功验证后导航到仪表板(http://localhost:4200/dashboard)。 现在,我有一种方法可以始终检查用户是否登录。 如果用户手动输入 => http://localhost:4200 ,我希望它重定向回仪表板,因为我用来跟踪用户的方法告诉我用户仍处于登录状态。如果未登录,用户将无法激活子组件. 我设置了警卫来保护我的路线,如下所示。

// Routes
export const routes: Routes = [ 
   { path: '', component: LoginComponent, pathMatch: 'full', data: { title: 'Login Page' },
     canActivate: [RedirectGuard] },
   { path: 'register', component: RegisterComponent },
   { path: '', component: ChildrenLayoutComponent, data: { title: 'Home' },
     runGuardsAndResolvers: 'always',
     canActivate: [AuthGuard],
     children: [
       {
          // Children component goes here
       }
     ]
   },
 ];

// RedirectGuard

@Injectable({
    providedIn: 'root'
})

export class RedirectGuard implements CanActivate {
    constructor(private authService: AuthService,
        private router: Router) {}

    canActivate() {
        if (this.authService.isLoggedIn()) {
            this.router.navigate(['/dashboard']);
            return true;
        }
        // console.log('You shall not pass!');
        this.router.navigate(['/']);
        return false;
    }
}

问题 我得到一个 msg => 限制导航以防止浏览器挂起。根据我的研究,这表明我在路由上有一个循环,因为我在 LoginComponent 上放置了 RedirectGuard。我试过canLoad,但这确实解决了我的问题。 请,如果用户登录并访问http://localhost:4200,即空路由路径,它应该将我重定向到仪表板。

感谢任何反馈。

【问题讨论】:

    标签: angular


    【解决方案1】:

    你需要这样的路线:

    {
        path: '',
        component: LoginComponent,
        pathMatch: 'full',
        data: { title: 'Login Page' },
        canActivate: [RedirectGuard]
    },
    {
        path: '/login',
        // other settings but do not use authGuard or redirectGuard here
    },
    // ... other routes
    

    现在,您的 RedirectGuard 正在将用户送回他们开始的位置 (''),因此它是一个循环。您需要一个安全的地方将他们发送到可以尚未经过身份验证的地方,以便他们可以登录,然后当他们再次点击 root ('') 时,他们会转到 /dashboard。此外,您实际上可以返回 urlTree,而不是调用 .navigate。

    canActivate() {
        if (this.authService.isLoggedIn()) {
            return this.router.createUrlTree(['/dashboard']);
        }
        // console.log('You shall not pass!');
        return this.router.createUrlTree(['/login']);
    }
    

    另外,我可能弄错了,但这条路线永远不会被使用,因为你的第一条路线总是会解决它:

    {
        path: '',
        component: ChildrenLayoutComponent,
        data: { title: 'Home' },
        runGuardsAndResolvers: 'always',
        canActivate: [AuthGuard],
        children: [
            {
                // Children component goes here
            }
        ]
    },
    

    https://angular.io/guide/router#milestone-5-route-guards

    【讨论】:

    • 非常感谢您的反馈。我已经尝试了您的建议,但问题仍然存在。
    • 尝试创建一个 stackblitz 示例并在此处发布。这会给我们一些可以修补和工作的东西。
    猜你喜欢
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多