这是我的棱角项目的路由器防护。基本上在我的系统中,我有许多用户角色。在警卫队中,我检查userProfile节点上的用户是否为isLawyer和isLawyerApproved。如果满足这些条件,则律师可以访问该路线。在canActivate函数中,我返回this.loggedin && this.isApproved。在我的登录组件中,我有一个ngOnit函数,该函数检查用户是否已经登录,如果已经登录,则重定向到/ dashboard路由。实际上,这不起作用,我希望如果通过身份验证的用户访问登录页面,则自动将其重定向到/ dashboard。请帮助我
class MyGuardService implements CanActivate{
loggedIn = false;
isApproved:boolean;
constructor(private authService:AuthService, private router:Router){
this.authService.isLogged().subscribe((response)=>{
if(response && response.uid){
this.loggedIn = true;
this.authService.getUserProfile(response.uid).valueChanges()
.subscribe(
(userProfile:UserProfile)=>{
if(userProfile.isLawyer && userProfile.isLawyerApproved){
this.isApproved = true;
}
}
)
}else{
this.loggedIn = false
}
}, (error)=>{
this.loggedIn = false;
})
}
canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean>|Promise<boolean>|boolean {
console.log('El abogado es aprobado??')
console.log(this.isApproved)
if(!this.loggedIn){
this.router.navigate(['/abogado-login']);
}
return (this.loggedIn && this.isApproved)
}
}
// LoginComponent
ngOnInit() {
this.authService.isLogged().subscribe((result)=>{
if(result && result.uid){
console.log('Estoy logueado debo redirigir');
this.router.navigate(['/abogado'])
}
})
}
答案 0 :(得分:3)
在您的gaurd中,只需在成功登录true或您遇到的任何情况后通过干扰路由器来添加重定向,然后将该gaurd放置在路由器模块的登录路由中即可。
constructor(private authService:AuthService, private router:Router){
this.authService.isLogged().subscribe((response)=>{
if(response && response.uid){
this.loggedIn = true;
this.authService.getUserProfile(response.uid).valueChanges()
.subscribe(
(userProfile:UserProfile)=>{
if(userProfile.isLawyer && userProfile.isLawyerApproved){
this.isApproved = true;
this.router.navigate(['/addroutewhereusershouldgowhenapproved']);
} else {
this.router.navigate(['/abogado']);
}
)
}else{
this.loggedIn = false
}
}, (error)=>{
this.loggedIn = false;
})
在路由器模块中,在路由路径上添加gaurd,如下所示。
{ path:'', component: LoginComponent, canActivate: [AuthGuard]}