Home > OS >  alternative way for canActivate in angular
alternative way for canActivate in angular

Time:06-23

In my angular 12 project, I have applied canActivate on routes but due to which routes are not working on browser page reload.

In canActivate , i am checking data is present or not in localStorage for currentUser. but when I reload page I didn't get value for localStorage item.

If I remove canActivate then page reload works fine.

Is there any other way in which I can prevent user for accessing routes if not logged in?

CodePudding user response:

You can try to check for logged in in NgOnInit() and redirect user to other route

As I know that for each route goes with a component and a component got NgOnInit() of the life cycle

CodePudding user response:

I think the best way to prevent the user from routing if not logged in is using sessionStorage since it is specific to the current session. But you can also use localStorage depending on your scenario. So you can do it like this:

In LoginComponent:

login(){

 if(this.username == "username" && this.password == "password"){
      sessionStorage.setItem('login', 'loggedOn');
         this.router.navigate(['/linkyouwant']);
 }
       
}

In your loginGuardService:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        

        if (sessionStorage.getItem('login') == 'loggedOn')
           return true;
        else {
           this._router.navigate(['/login']);
           return false;
        }
    }
  • Related