1

I tried to create a canActivate method to protect my routes, for my Angular application. I want to check the status of the user,(My backend is firebase, user authentication, log in , sign up are implemented using fire base) whether logged in or not, so I wrote the following code

constructor (private router: Router, private auth: AngularFireAuth) { 
    this.y = false;
    this.auth.authState.subscribe(x => {
      
      if(x == null){
        console.log("null if condition") // to track the program path
        this.y =  false;
        
      }
      else{
        console.log("else condition") // to track the program path
        this.y= true;
        
      }
      
      console.log("inside fun",this.y); // to track the program path
    })

  }

  canActivate(route:any, state: RouterStateSnapshot) {

    console.log("canActivate", this.y); // to track the program path
    if (this.y)
    { return true}
    else
    {
      this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
      return false;

    }
    
  }

I want to elaborate the situation. Let's say, If the user is logged in, then the value of y changes inside the subscription but once it comes out it reverts back to it initialized value. Pls help me with this.

  • Almost certainly a duplicate of [*Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference*](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) but the question isn't quite clear enough to be 100% sure. – T.J. Crowder Mar 31 '22 at 07:44
  • I think the problem is that you are running asynchronous code in your constructor, and the code in can activate has not yet the real value when it runs. So you should make your can active method return Observable and implement the code inside the constructor in the canActivate method – Bruno Miguel Mar 31 '22 at 08:16

1 Answers1

0

I don't think it should be done like that when it comes to Firebase/Angular. There is a Github repository called AngularFire where you can do this with a single line of code

{ path: 'items',        component: ItemListComponent, ...canActivate(redirectUnauthorizedToLogin) },

This will help you redirect non authorized users to a different route, but you can do advanced stuff using the authgards delivered with the package

Mohammed
  • 171
  • 2
  • 11