title: Angular 2/4 - Storing the Current User Object Details in front-end (rather than making continuous HTTP requests to back-end)
body: <p>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. </p>
  
  <p>I have added a UserService class which sets/updates a currentUser object when a method in the class is called.</p>
  
  <pre><code>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 =&gt; {
          this.currentUser = data;
      });
    }
  
  }
  </code></pre>
  
  <p>I have found this method to cause a race condition problems. For example, an error occurs if the <code>currentUser.username</code> is requested in the profile component but the service class hasn't completed the request yet.</p>
  
  <p>I've also tried checking if the <code>currentUser</code> is undefined and then calling the <code>updateCurrentUser()</code> but it doesn't seem to work.</p>
  
  <pre><code>if(this.userService.currentUser === undefined){
      this.userService.updateCurrentUser();
  } 
  </code></pre>
  
  <p><br />
  <b>Update:</b>The error message shown in the browser console
  <a href="https://i.stack.imgur.com/K0ioy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K0ioy.png" alt="enter image description here"></a></p>
  
  <p><br />
  <b>Update on HTML used:</b><br/>
  I am using data binding to display the username (calling it directly from the UserService class). E.g.</p>
  
  <pre><code>&lt;span class="username-block"&gt;{{userService.currentUser.username}}&lt;/span&gt;
  </code></pre>
  
  <p>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.</p>
  
  <p><br />
  I would appreciate any help/feedback.</p>