I am using the Angularfire2 library to sign in the user and fetch the data from the Firebase DB but when the user hits sign out the following error is thrown to console:
Cannot read property 'uid' of null at line
Here is the uid
property throwing the error at line 2 of the ngOnInit
method of the tasks component:
ngOnInit() {
this.authSub1 = this.auth.authState.subscribe((auth) => {
this.tasksSub = this.af.list(`users/${auth.uid}/tasks`, { preserveSnapshot: true }).subscribe(snapshots => {
snapshots.forEach(snapshot => {
this.tasksArray.push(snapshot.val().name);
});
});
}, (err) => {this.openSnackBar(); console.log(err); });
}
And then I call unsbuscribe
on the above subscription to avoid memory leaks at the ngOnDestroy
method:
ngOnDestroy() {
this.authSub1.unsubscribe();
}
Here is the sign out method triggered by the button which is located on the main component (router outlet of the main component is showing the above component):
logout() {
this.auth.auth.signOut()
.then(() => {
this.router.navigateByUrl('/login');
})
.catch(function(err) {console.log(err); });
}
Found it! The solution is pretty simple:
to avoid the user id to be null when the user hits log out I had just to avoid using the uid
from the authState.subscribe
callback parameter and just use a newly created variable instead that stores the uid
directly from the injected AngularFireAuth
service on ngOnInit
:
this.userId = this.auth.auth.currentUser.uid;