【发布时间】: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