I want my entire app to have the same nav bar, so naturally I put it in app.component.html. This nav bar contains the email of the logged user, and so should appear on the nav bar after connection. In order to keep that info even after a page refresh, I keep the email in session storage.
The thing is that, in order for the HTML code to pick up the value added in session storage after logging in, app.component has to refresh. But it's not happening when going to the next page after logging in. I have to refresh the page for the info to appear on the navbar, and I clearly don't want to do that.
I could create a nav bar component, but I don't want to have to include it everywhere on the app, even though it would somewhat solve my problem.
Some code next, just to visualize things a bit better
I recommend you using a simple EventEmitter or RxJS Subject/BehaviorSubject.
user = new BehaviorSubject<User>(null);
this user will be a property of you auth service.
each time a user successfully signed-up or logged-in, you will notify all the
subscribers with the new value.
this.user.next(user);
and for the auto-login, auto-logout functionality you may use localStorage
localStorage.setItem('userData', JSON.stringify(user));
wherever you need the current user, for example on navbar, subscribe to it and it will gives you the latest changes.
this.userSub = this.authService.user.subscribe(user => {
});
and finally make sure unsubscribe from user subscription wherever you subscribed
ngOnDestroy() {
this.userSub.unsubscribe();
}
for auto-login functionality, even if the page refreshed, we stored current user object in local-storage whenever user logged-in/signed-up successfully, so by using ngOnInit
hook on the app.component (a parental component) we can achieve what you need by retrieving and restoring the user object to angular-app.
autoLogin() {
const userData = JSON.parse(localStorage.getItem('userData'));
if (!userData) {
return;
}
const loadedUser = new User(
userData.email,
userData.token,
new Date(userData.expiresIn)
);
if (loadedUser.token) {
this.user.next(loadedUser);
}
}
you may check token validity and expiresIn before emitting the restored user.
make sure to call autoLogin() as the angular-app starts.