对不起,我不知道如何使代码更紧凑,因为我不知道自己做错了什么。因此,我制作了一个角形5应用程序,我用一个简单的表单登录了一个admin-login-component.ts on /admin,它允许您登录到另一个路由/管理/概述,我阻止非登录用户转到管理/概述,并将它们重定向到/admin,但在某些地方,我搞砸了,现在当我登录时,我看到路由更改为/ admin /概述,但我仍然看到管理组件,我错过了什么?
app-routing.module.ts
{
path: 'admin',
component: AdminLoginComponent,
data: {title: 'Admin'},
children: [
{
path: 'overview',
component: AdminOverviewComponent,
canActivate: [AuthGuard],
data: {title: 'Overview'}
}
]
}admin-login-component.ts
export class AdminLoginComponent{
constructor(private router: Router, private service: AuthService){}
loginUser(e) {
e.preventDefault();
let username = e.target.elements[0].value;
let password = e.target.elements[1].value;
if(username == 'test' && password == 'test'){
this.service.login();
this.router.navigate(['admin/overview']);
}
}
}auth.service.ts
@Injectable()
export class AuthService {
isLoggedIn = false;
// store the URL so we can redirect after logging in
redirectUrl: string;
login(): Observable<boolean> {
return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
}
logout(): void {
this.isLoggedIn = false;
}
}八月-警卫服务
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
boolean {
let url: string = state.url;
return this.checkLogin(url);
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.canActivate(route, state);
}
checkLogin(url: string): boolean {
if (this.authService.isLoggedIn) { return true; }
// Store the attempted URL for redirecting
this.authService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/admin']);
return false;
}
}发布于 2018-03-28 09:19:27
通过将路由更改为
{
path: 'admin',
component: AdminLoginComponent,
data: {title: 'Admin'}
},
{
path: 'admin/overview',
component: AdminOverviewComponent,
canActivate: [AuthGuard],
data: {title: 'Overview'}
}当我将概览定义为管理/概述而不是子路由时,它可以工作。
发布于 2018-03-27 19:50:48
在您的loginUser方法中,您尝试直接导航,而不等待(假)登录过程完成。
因此,当用户尚未被视为登录时,您的保护就会被触发,从而阻止激活另一个组件。
试试看
this.service.login().subscribe(userIsLoggedIn =>
this.router.navigate(['admin/overview']));https://stackoverflow.com/questions/49518906
复制相似问题