Just starting out with angular and facing a seemingly simple issue that I can't seem to solve despite trying various solutions found on SO. I have created a login component where upon submission, the user is redirected to their profile page. While I am able to successfully redirect the user, the navigation bar at the top does not auto-refresh as intended. My goal is to have the navigation bar show the "Logout" button instead of the "Login/Register" button once the user logs in. Here's how my code files are structured:
login-page.component.html
<form #loginForm="ngForm" (ngSubmit)="loginUser(loginForm)" id="loginForm" class="loginbackground">
<input ngModel #emailAddress="ngModel" type="text" autocomplete="off" placeholder="Email" id="emailAddress" name="emailAddress" />
<button type="submit" id="submit">LOGIN</button>
login-page.component.ts
@Output() refreshEvent = new EventEmitter<any>();
loginUser(event) {
// Validations. If successful, proceed
const formData = event.value;
this.auth.loginUser(formData);
.subscribe(data => {
localStorage.setItem('loggedUser', JSON.stringify(data.userdata));
// Form submit action here
if (data.userdata.resMsg === 'Login failed') {
this.errorPopup = true;
this.errorText = 'Email Address and Password do not match';
} else {
this.refreshEvent.emit();
this.emailAvailable = true;
this.showLogin = false;
this.showRegister = false;
this.router.navigateByUrl('/404', { skipLocationChange: true }).then(() =>
this.router.navigate(['user-profile']));
}
});
});
}
Problem
The issue arises when the nav bar doesn't update automatically after login. Manually refreshing the page resolves the problem but that's not ideal. I need the nav bar to reflect changes upon user login without needing manual intervention.
What I've tried
- I attempted to implement the solution suggested here, but it didn't work for me.
- Despite using an event emitter as shown above, I couldn't get it to function properly.
- I also experimented with reloading the entire page using
ngOnInit()
to refresh the navigation bar component, but it caused an infinite loop. This was obviously a workaround, but I explored it nonetheless.
Is there a more elegant and effective way to achieve the desired outcome?