title: Logout when closing window in Angular 4
body: <p>I have an Angular 4 applicaton and I want to call the logout function when the user close the page (window or tab of the browser).</p>
  
  <p>This is my logout function : </p>
  
  <pre><code>    let currentUser: User = JSON.parse(localStorage.getItem('currentUser'));
  
      let headers = new Headers({ 'Authorization': 'Basic ' +  btoa(currentUser.login + ":" + currentUser.password),
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': 'access-control-allow-headers, access-control-allow-origin, content-type, authorization'
      });
  
      let opts = new RequestOptions();
      opts.headers = headers;
  
  
     return this.http.get(this.route + 'UserLogout', opts).map((response: Response) =&gt; response.json());
  }
  </code></pre>
  
  <p>And in my app.component.ts, I have :</p>
  
  <pre><code>@HostListener('window:beforeunload', ['$event'])
  beforeUnloadHander(event) {
      this.authenticationService.logoutOnClose().subscribe(res=&gt; {
          localStorage.removeItem('currentUser');
      });
  
  }
  </code></pre>
  
  <p>But the window is close and the request is never done. I think I need to do the request synchronously but I don't know how to do it.</p>
  
  <p>Do you have an idea ?</p>
  
  <p><strong>EDIT</strong>
  I tried with jQuery :</p>
  
  <pre><code> ngOnDestroy(){
      let currentUser: User = JSON.parse(localStorage.getItem('currentUser'));
      $.ajax({ url: 'myURL',
          beforeSend: function(request) {
              request.setRequestHeader("Authority", 'Basic ' +  btoa(currentUser.login + ":" + currentUser.password));
              request.setRequestHeader('Content-Type', 'application/json');
              request.setRequestHeader('Access-Control-Allow-Origin', '*');
              request.setRequestHeader('Access-Control-Allow-Headers', 'access-control-allow-headers, access-control-allow-origin, content-type, authorization');
          },
          type: 'GET',
          success: function (result) {
          alert('test');
          localStorage.removeItem('currentUser');
      }, async: false });
  }
  </code></pre>