Below is the content of my app.component.html
:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class='container'>
<ul class="nav navbar-nav">
<li class='nav-item'>
<a class='nav-link' routerLink="/">Home</a>
</li>
<li class='nav-item'>
<a class='nav-link' routerLink="/about">About</a>
</li>
<li class='nav-item' *ngIf='!user'>
<a class='nav-link' routerLink="/login">Login</a>
</li>
<li class='nav-item' *ngIf='!user'>
<a class='nav-link' routerLink="/register">Register</a>
</li>
<li class='nav-item' *ngIf='user'>
<a class='nav-link' routerLink="/logout">Logout</a>
</li>
</ul>
</div>
</nav>
<main>
<router-outlet></router-outlet>
</main>
I am attempting to display the /logout
button when the user is logged in, and hide it otherwise. Similarly, I want to show the /login
and /register
buttons if the user is not logged in.
This is how my login logic looks:
import {Component} from '@angular/core';
import {AuthService} from '../core/auth.service';
import {Router, Params} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'page-login',
templateUrl: 'login.component.html',
styleUrls: ['login.scss']
})
export class LoginComponent {
loginForm: FormGroup;
errorMessage: string = '';
constructor(
public authService: AuthService,
private router: Router,
private fb: FormBuilder
) {
this.createForm();
}
createForm() {
this.loginForm = this.fb.group({
email: ['', Validators.required],
password: ['', Validators.required]
});
}
tryFacebookLogin() {
this.authService.doFacebookLogin()
.then(res => {
this.router.navigate(['/user']);
});
}
tryTwitterLogin() {
this.authService.doTwitterLogin()
.then(res => {
this.router.navigate(['/user']);
});
}
tryGoogleLogin() {
this.authService.doGoogleLogin()
.then(res => {
this.router.navigate(['/user']);
});
}
tryLogin(value) {
this.authService.doLogin(value)
.then(res => {
this.router.navigate(['/user']);
}, err => {
console.log(err);
this.errorMessage = err.message;
});
}
}
An example of the doLogin
function is provided below:
doLogin(value){
return new Promise<any>((resolve, reject) => {
firebase.auth().signInWithEmailAndPassword(value.email, value.password)
.then(res => {
resolve(res);
}, err => reject(err))
})
}
I come from an Express background and I'm relatively new to Angular. In Express, I would typically use a session variable to track whether a user is logged in or not. How can I achieve something similar in Angular?