这是我的 Angular 项目的路由器守卫。基本上在我的系统中我有很多用户 Angular 色。在守卫中,如果用户是 Lawyer 和 isLawyerApproved,我会检查 userProfile 节点。如果这些条件成立,律师就可以访问该路由。在 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)
}
}
//登录组件
ngOnInit() {
this.authService.isLogged().subscribe((result)=>{
if(result && result.uid){
console.log('Estoy logueado debo redirigir');
this.router.navigate(['/abogado'])
}
})
}
最佳答案
在您的 gaurd 中,只需在登录成功时通过 improting router 添加重定向,或者您的任何条件,并将该 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;
})
在路由器模块中,在路由路径上添加类似下面的东西。
{ path:'', component: LoginComponent, canActivate: [AuthGuard]}
关于如果用户已经登录,Angular 登录组件重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51941918/