I implemented angular firebase email and password registration and login, but now what I want to do is check in my navigation template the state of the user, if the user is logged in, then hide login button, as well as hide register button. I tried googling for some tutorials on this, and found out that I must use AuthService and AuthInfo as you can see here:
The thing is that they are using a lot of promises and stuff, which I'm not familiar with and it really confuses me. I'm trying to achieve this in the most basic way and looking for someone to guide me and help me.
Here is my code now:
navigation -
<ul class="nav navbar-nav">
<li><a routerLink="" routerLinkActive="active">Home</a></li>
<li><a routerLink="login" routerLinkActive="active" *ngIf="!authInfo?.isLoggedIn()">Login</a></li>
<li><a routerLink="register" routerLinkActive="active" *ngIf="!authInfo?.isLoggedIn()">Register</a></li>
<li><a routerLink="quiz" routerLinkActive="active">Quiz</a></li>
</ul>
My Auth service file with all the user create and login to firebase logic -
@Injectable({
providedIn: 'root'
})
export class AuthService {
private user: Observable<firebase.User>;
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
this.user = _firebaseAuth.authState;
this.user.subscribe(
(user) => {
if (user) {
this.userDetails = user;
console.log(this.userDetails);
} else {
this.userDetails = null;
}
}
);
}
logUserIn(email, pass) {
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("error" + error);
})
if (this.userDetails) {
email = this.userDetails.email;
console.log("hello im user" + " " + email);
} else {
console.log("not working");
}
this.router.navigate(['']);
}
regUser(email, pass) {
firebase.auth().createUserWithEmailAndPassword(email, pass)
.catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});
}
}
Login component -
@Component({
selector: 'login',
templateUrl: 'login.component.html'
})
export class LoginComponent {
form: FormGroup;
constructor(fb: FormBuilder, private _loginService: LoginService, private auth: AuthService) {
this.form = fb.group({
email: ['', Validators.required],
password: ['', Validators.compose([Validators.required,
PasswordValidator.cannotContainSpace])]
})
}
login() {
this.auth.logUserIn(this.form.value.email, this.form.value.password);
};
}
auth-info.ts file from the github link above -
export class AuthInfo {
constructor(public $uid: string) { }
isLoggedIn() {
return !!this.$uid;
}
}
EDIT:
So thanks to Tushar Walzade I managed to show and hide these buttons, but I get really weird behaviour. There are no problems when logging out, but when I login, nothing happens, I get not working message to Chrome console which comes from my logUserIn method in Auth service. But when I refresh page one time, then it shows me that it's working, I get user information details in console and buttons get hidden. I don't know why this happens, but I think this might be something with sessionStorage which I know nothing about.
Here is the code:
Auth service
export class AuthService {
private user: Observable<firebase.User>;
private userDetails: firebase.User = null;
public loggedIn = false;
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
this.user = _firebaseAuth.authState;
this.loggedIn = !!sessionStorage.getItem('user');
this.user.subscribe(
(user) => {
if (user) {
this.userDetails = user;
console.log(this.userDetails);
} else {
this.userDetails = null;
}
}
);
}
// Set current user in your session after a successful login
setCurrentUser(email: string): void {
sessionStorage.setItem('user', email);
this.loggedIn = true;
}
// Get currently logged in user from session
getCurrentUser(): string | any {
return sessionStorage.getItem('user') || undefined;
}
isLoggedIn() {
return this.loggedIn;
}
logUserIn(email, pass) {
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("error" + error);
})
//var user = firebase.auth().currentUser;
//var email;
if (this.userDetails) {
email = this.userDetails.email;
console.log("hello im user" + " " + email);
//email = user.email;
this.setCurrentUser(email);
this.loggedIn = true;
} else {
console.log("not working");
}
this.router.navigate(['']);
}
regUser(email, pass) {
firebase.auth().createUserWithEmailAndPassword(email, pass)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
//console.log(this.form.controls['email'].value);
}
logOut() {
this.loggedIn = false;
firebase.auth().signOut().then(function() {
// Sign-out successful.
console.log("signout successful");
}).catch(function(error) {
// An error happened.
console.log("error happened");
});
}
}
Login component
export class LoginComponent {
form: FormGroup;
constructor(fb: FormBuilder, private _loginService: LoginService, private auth: AuthService){
this.form = fb.group({
email:['',Validators.required ],
password:['',Validators.compose([Validators.required,
PasswordValidator.cannotContainSpace])] })
}
login(){
this.auth.logUserIn(this.form.value.email, this.form.value.password);
};
}
app.component.ts because I have my router outlet and links in app.component.html
export class AppComponent {
title = 'angular-draganddrop';
constructor(private auth: AuthService) { }
LoggedIn() {
return this.auth.isLoggedIn();
}
logout() {
return this.auth.logOut();
}
}
EDIT EDIT:
So I checked application session storage in Chrome and when I log out I indeed see my user email still there. I have to delete it by hand. Then when trying to log in first time it doesn't work and there is also no user email in session storage. Second time it gets added. The login system was working fine until adding sessionStorage functionality to code so it's definitely related to it. I don't know how sessionStorage works so I'm looking for a help to solve this.