A login-logout application is currently being developed, with a navbar component that needs to update its view template based on the user's login status. The UserService service class contains a logout method. Here is a snippet of the Navbar component:
export class NavbarComponent implements OnInit {
loginStatus: boolean;
constructor(private _userService: UserService) { }
ngOnInit() {
this._userService.loginStatus().subscribe((data)=>{
this.loginStatus = data;
console.log('You are logged in:'+this.loginStatus)
})
setTimeout(()=>{
this._userService.logout();
}, 10000)// example usage for calling logout
}
}
The UserService code snippet:
@Injectable()
export class UserService {
private _token: string = null;
set token(token) {
localStorage.setItem('token', token);
this._token = token;
this.loggedIn = true;
}
get token() {
if (this._token) {
return this._token;
}
return this._token = localStorage.getItem('token');
}
private loggedIn: boolean = true;
constructor(private _httpClient: HttpClient) { }
logout(){
console.log('out')
this._token = null;
this.loggedIn = false;
localStorage.removeItem('token');
localStorage.clear();
}
loginStatus(): Observable<boolean>{
let observable: Observable<boolean> = new Observable((observer) => {
observer.next(this.loggedIn);
})
return observable;
}
}
The loginStatus() method returns an observable subscribed in the Navbar component. An issue arises when logging out using the logout method - I need the loginStatus() method to emit data again. How can changes be detected in the loggedIn property to make the observable emit data? Any suggestions or alternative solutions would be greatly appreciated. Thank you.