Having an issue with using a Subject to track if a user is authenticated. The problem arises when the subject returns undefined upon reloading after subscribing in a component.
Below is my approach: I check for user data in local storage and set the Subject to true if the data is present.
user.service.ts
public auth_status:Subject<boolean> = new Subject<boolean>();
getCurrentUser(): User {
let storage = localStorage.getItem('current_user');
if (storage) {
return Json.parse(storage);
} else {
return null
}
};
getUserAuth() {
if (this.getCurrentUser() != null) {
this.auth_status.next(true);
console.log(this.auth_status);
} else {
this.auth_status.next(false);
console.log(this.auth_status);
}
return this.auth_status;
}
navbar.component.ts
constructor(private _userService: UserService) {
this._userService.getUserAuth().subscribe(data => this.auth_status = data);
}
this.auth_status controls an *ngIf in the navbar which displays either a sign-in or sign-out button
I've also attempted calling the method before subscribing, but it didn't resolve the issue.
Any insights are appreciated! Thanks!