I would like an efficient way to store (and update) the current user details in the frontend, rather than making new HTTP GET requests to the backend whenever a new component is loaded.
I have added a UserService class which sets/updates a currentUser object when a method in 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;
});
}
}
I have found this method to cause a race condition problems. For example, an error occurs if the currentUser.username
is requested in the profile component but the service class hasn't completed the request yet.
I've also tried checking if the currentUser
is undefined and then calling the updateCurrentUser()
but it doesn't seem to work.
if(this.userService.currentUser === undefined){
this.userService.updateCurrentUser();
}
Update:The error message shown in the browser console
Update on HTML used:
I am using data binding to display the username (calling it directly from the UserService class). E.g.
<span class="username-block">{{userService.currentUser.username}}</span>
I have also tried assigning the currentUser object to a variable within the component that I trying to display the username but it has the same result.
I would appreciate any help/feedback.