'My var does not gets updated even after changing it inside my subscription Angular, Firebase
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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammed |
