首页 > 解决方案 > 如果用户登录,如何保护登录和注册组件?

问题描述

我有登录注册和其他一些与其组件相关的路由。我可以保护 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']);
    }
  }

  }

标签: angulartypescript

解决方案


如我所见,您已经写了,AuthGuard那么您只需检查AuthGuard用户是否已经登录。如果用户已登录,则返回,false否则返回true


推荐阅读