0

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?

ganesh
  • 416
  • 1
  • 11
  • 32
  • 2
    I believe you are falling into the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) ? – subodhkalika Jun 23 '22 at 06:33

2 Answers2

-1

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;
        }
    }
Abdulwehab
  • 1,356
  • 2
  • 10
  • 12
-2

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

Bùi Anh Khoa
  • 82
  • 1
  • 5