title: How to wait for a http request to finish in Angular?
body: <p>I've been building a SPA with Angular 4 on the front end and ASP.NET Core 2 on the Backend. Basically, I'm trying to automatically renew an user login, given a valid token. When I reload a page, for example, I would like that Angular stayed logged in. I'm storing the token on local storage, as well as an user object so I can check some user properties (if he/she is logged in for example).</p>
  
  <p>How should I force angular to wait for the http request to finish?
  Here's the .net get Service:</p>
  
  <pre><code>get&lt;T&gt;(url: string): Observable&lt;T&gt; {
      let options = this.doHeaders();
      return this.doSub(this.http.get(this.doUrl(url), options));
  }
  
  private doSub&lt;T&gt;(obs: Observable&lt;Response&gt;) {
      var ob1: Observable&lt;T&gt; = obs.map(this.extractData)
          .catch(this.handleError);
  
      return ob1;
  }
  </code></pre>
  
  <p>Here's the HTTP Request code:</p>
  
  <pre><code>   getUser() {
  
      if (this.storage.token == null || this.storage.token == '') {
          return;
      }
  
      this.net.get&lt;LoginModel&gt;(`Authentication/GetUser`).subscribe(t =&gt; {
          this.storage.token = t.token;
          this.storage.user = t.user;
          console.log(this.storage.user);
      });
  }
  </code></pre>
  
  <p>Here's how I'm checking for the user:</p>
  
  <pre><code>export class StorageService {
  
      constructor(
          private storage: LocalStorageService
      ) {
      }
  
      public user: User = null;
  
      public get isLoggedIn(): boolean {
          return this.user != null;
      }
  </code></pre>
  
  <p>}</p>
  
  <pre><code>export class IsLoggedIn implements CanActivate {
  
  constructor(
      private storage: StorageService,
      private router: Router
  ) { }
  
  canActivate(
      childRoute: ActivatedRouteSnapshot,
      state: RouterStateSnapshot
  ) {
      if (this.storage.isLoggedIn) {
          return true;
      }
  
      this.router.navigate(['account/login'], {
          queryParams: {
              return: state.url,
              message: 'You must be logged in'
          }
      });
      return false;
  }}
  </code></pre>
  
  <p>The real issue is: Whenever I try to reload the page on a protected page, Angular does not wait for the http to complete, and redirects me to the login page. After about a few seconds, it logs in, but i've been redirected already.
  The above code is being executed on AppComponent (NgOnInit). Thanks in advance.</p>