angular - 如果用户登录,如何保护登录和注册组件?
问题描述
我有登录注册和其他一些与其组件相关的路由。我可以保护 loginComponent 下的其他路由,但如果用户登录并注册,我不希望用户通过手动更改 url 来查看登录组件。
用户可以通过在 URL 上发短信“/”来进入登录组件,如果用户 LoggedIn,我想防止这种情况发生
下面是我的路线配置
export const appRoutes: Routes = [
{path:'',component:LoginComponent},
{
path:'',
canActivate:[AuthGuard],
children:[
{path: 'home', component: HomeComponent},
{path: 'appointments', component: AppointmentsComponent},
{path: 'appointmentPicker', component: AppointmentPickerComponent},
]
},
{path:'register',component:RegisterComponent},
{path:'**',redirectTo:'home',pathMatch:'full'},
];
AuthGuard
export class AuthGuard implements CanActivate {
constructor(private authService:AuthService,private router:Router){
}
canActivate(): boolean{
if(this.authService.loggedIn()){
return true;
}
else{
this.router.navigate(['']);
}
}
}
解决方案(更新) 这是我尝试和工作的完全我想要的。谢谢大家
export class LoginComponent implements OnInit {
model:any={};
tokenExist:boolean=false;
logInWorked:boolean=false;
constructor(private authService:AuthService,private router:Router) {
}
login()
{
console.log(this.model);
this.authService.login(this.model).subscribe(value=>{
this.router.navigate(['/home']);
this.logInWorked=true;
}
)
}
ngOnInit() {
if(this.logInWorked!=true && this.authService.loggedIn()){
this.router.navigate(['/home']);
}
}
}
解决方案
如我所见,您已经写了,AuthGuard
那么您只需检查AuthGuard
用户是否已经登录。如果用户已登录,则返回,false
否则返回true
。
推荐阅读
- ocaml - 致命错误:调试器不支持通道锁
- nltk - 即使使用 POS 标签,Nltk Wordnet 也不会对单词进行词形还原
- python - tf.keras“历史未定义”......但在我看来它已被定义
- java - EasyRandom 集合大小错误?
- swift - SwiftUI 中 CoreData 列表项的详细视图
- java - Java Micrometer @Counted - @ExceptionHandler 的 exception="none" 和 result="success"?
- tensorflow - 如何使用 gpu 并行训练 tensorflow.keras 模型?TensorFlow 版本 2.5.0
- java - Java:Canvas.drawline,如何画粗线
- database - 此数据库的类型
- python - fastapi + sqlalchemy + pydantic → 如何处理多对多关系