首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角5的认证

角5的认证
EN

Stack Overflow用户
提问于 2018-03-27 17:19:17
回答 2查看 449关注 0票数 0

对不起,我不知道如何使代码更紧凑,因为我不知道自己做错了什么。因此,我制作了一个角形5应用程序,我用一个简单的表单登录了一个admin-login-component.ts on /admin,它允许您登录到另一个路由/管理/概述,我阻止非登录用户转到管理/概述,并将它们重定向到/admin,但在某些地方,我搞砸了,现在当我登录时,我看到路由更改为/ admin /概述,但我仍然看到管理组件,我错过了什么?

app-routing.module.ts

代码语言:javascript
复制
{
path: 'admin',
component: AdminLoginComponent,
data: {title: 'Admin'},
children: [
  {
    path: 'overview',
    component: AdminOverviewComponent,
    canActivate: [AuthGuard],
    data: {title: 'Overview'}
  }
]
}

admin-login-component.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
@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;
 }
}

八月-警卫服务

代码语言:javascript
复制
@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;
  }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-28 09:19:27

通过将路由更改为

代码语言:javascript
复制
{
  path: 'admin',
  component: AdminLoginComponent,
  data: {title: 'Admin'}
},
{
  path: 'admin/overview',
  component: AdminOverviewComponent,
  canActivate: [AuthGuard],
  data: {title: 'Overview'}
}

当我将概览定义为管理/概述而不是子路由时,它可以工作。

票数 0
EN

Stack Overflow用户

发布于 2018-03-27 19:50:48

在您的loginUser方法中,您尝试直接导航,而不等待(假)登录过程完成。

因此,当用户尚未被视为登录时,您的保护就会被触发,从而阻止激活另一个组件。

试试看

代码语言:javascript
复制
this.service.login().subscribe(userIsLoggedIn =>
 this.router.navigate(['admin/overview']));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49518906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档