Hey there, I'm currently facing an issue with displaying the logged-in user's username in the navbar. The username is not updating immediately after logging in or out. To resolve this issue, I decided to use rxjs's Subject and Observable. Surprisingly, it works perfectly when I log out, but not when I log back in. As a newbie to Angular, I'm not sure what could be causing this problem. Can anyone provide some insights?
navbar.component.ts
constructor(
private authService: AuthService,
private router: Router,
private flashMessage: FlashMessagesService,
private toastrService: ToastrService
) {
this.auth = authService;
authService.isLoggedIn().subscribe(
status => {
if(status == false) {
this.user = null;
} else {
this.authService.getProfile().subscribe(profile => {
this.user = profile.user;
})
}
}
)
}
auth.service.ts
private logger = new Subject<boolean>();
isLoggedIn(): Observable<boolean> {
return this.logger.asObservable();
}
setLoginLogger(status){
this.logger.next(status)
}
logout(){
this.authToken = null;
this.user = null;
localStorage.clear();
this.logger.next(false);
}
authenticateUser(user){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/users/authenticate', user, {headers: headers})
.map(res => res.json());
}
storeUserData(token, user){
localStorage.setItem('id_token', token);
localStorage.setItem('user', JSON.stringify(user));
this.authToken = token;
this.user = user;
}
login.component.ts
onLoginSubmit(){
const user = {
username: this.username,
password: this.password
}
this.authService.authenticateUser(user).subscribe((data) => {
if(data.success){
this.authService.storeUserData(data.token, data.user);
if(localStorage.getItem('id_token')){
this.authService.setLoginLogger(true);
this.router.navigate(['']);
this.toastrService.success('Hello world!', 'Toastr fun!');
}
} else {
this.toastrService.success('Hello world!', 'Toastr fun!');
this.router.navigate(['login']);
}
})
}