So, I am very close to understanding this. Basically, I have a login, and I have a code setting for viewing onAuthStateChanged, but the problem is that when I refresh the page, even if the user is currently logged in, it still redirects to the /login page, because The auth guard that I have set up checks to see if the user is logged in.
I have an authentication service that does all authentication.
In my auth service constructor, where I have my onAuthStateChanged setting onAuthStateChanged :
constructor( private auth: AngularFireAuth, private router:Router, private db:AngularFireDatabase, ) { firebase.auth().onAuthStateChanged(function(user) { if (user) {
Here is my canActivate() protection method:
canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean> { if(this.authService.getAuthenticated()) { return Observable.of(true); } else { this.router.navigate(['/login']); } }
And here is the getAuthenticated() method:
getAuthenticated() { return firebase.auth().currentUser; }
Update:
Here are the methods that are called when a user logs in. In the actual component, the login method is used here:
login(data, isValid) { if(isValid) { this.authService.login(data.email, data.password) .then( (data) => { console.log('data', data); this.router.navigate(['/projects']) }, error => { this._utilities.createToasty({ msg: "The email/password combination is incorrect.", type: "error" }); } ); } }
And in the auth service, here is the login method:
login(email, password) { return firebase.auth().signInWithEmailAndPassword(email, password); }
So right now, I'm not quite sure what code I need to put in to make sure that when my user refreshes the page, the auth defender takes care of this and actually allows the user to go on the route, and not always redirect to the /login route.
Thoughts?