登录我有这样的路线:角2重定向用户是否在
const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
和AuthGuard
:
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private router: Router,
private authService: AuthService) { }
canActivate() {
if (this.authService.isLoggedIn()) {
return true;
}
this.router.navigate(['login']);
return false;
}
}
当用户访问该网站时,他被重定向到登录页面。当用户尝试访问/dashboard
路由而没有验证时也会发生同样的情况。如果他已登录,如何将用户重定向到/dashboard
?例如,当我访问myapp.com
并且我已登录时,我想将其重定向到myapp.com/dashboard
。
上'canActivate'将无法正常工作这样做呢? 'if(this.authService.isLoggedIn()){this.router.navigate(['dashboard']);返回true; }'。 – developer033
@ developer033,我试过了,它不起作用!会有一个无限循环。 –
嗯,所以你只能在你的'LoginComponent'(在'ngOnInit')上检查它.. – developer033