【发布时间】:2018-03-27 17:19:17
【问题描述】:
对不起,我不知道如何使它更紧凑,因为我不知道我做错了什么。因此,我制作了一个 Angular 5 应用程序,并在路由 /admin 上创建了一个admin-login-component.ts,并使用简单的表单登录操作登录,该操作可让您转到另一条路由 /admin/overview 并阻止未登录的用户转到admin/overview 并将它们重定向到 /admin 但在某处我搞砸了,现在当我登录时,我看到路由更改为 /admin/overview 但我仍然看到管理组件,我错过了什么?
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;
}
}
【问题讨论】:
-
您的管理员登录组件中有路由器插座吗?
-
不只有app.router,登录里面有router outlet是不是更好?
-
否,但这可能是您在登录页面上看到其他组件的原因。你有没有在下面尝试我的答案?
-
我目前在工作,npm 我没有通过代理,所以我必须设置代理设置,但我是这样的菜鸟,所以任何线索我如何定义和找到代理?
标签: angular authentication angular5