Is there a more efficient way to store and update the current user details in the frontend, without constantly making new HTTP GET requests to the backend every time a new component loads?
The solution I came up with is a UserService class that handles setting and updating a currentUser object whenever a method inside the class is called.
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
@Injectable()
export class UserService {
public currentUser: any;
constructor(private http: Http) { }
updateCurrentUser() {
this.http.get('api/login/currentUser').subscribe(data => {
this.currentUser = data;
});
}
}
However, this approach has resulted in race condition problems. For instance, if the profile component tries to access currentUser.username
before the service class completes the request, an error occurs.
I attempted to resolve this issue by checking if currentUser
is undefined and then calling updateCurrentUser()
, but it did not solve the problem.
if(this.userService.currentUser === undefined){
this.userService.updateCurrentUser();
}
Update:An error message is displayed in the browser console
https://i.sstatic.net/K0ioy.png
Further Details:
I am using data binding to show the username directly from the UserService class. For example:
<span class="username-block">{{userService.currentUser.username}}</span>
I also attempted assigning the currentUser object to a variable within the component attempting to display the username, but encountered the same outcome.
Any suggestions or feedback would be greatly appreciated.