title: Perform an asynchronous service get when closing browser window / tab with Angular
body: <p>I'm currently trying to make an Angular app make an API service call when the user tries to navigate away from my page. Either by closing the tab / window, or typing in an external URL.</p>
  
  <p>I've tried to implement several different ways I've seen described here on stackoverflow questions, but none seem to have the desired effect. Some mention sync ajax requests which have been, or are in the process of being deprecated in onbeforeunload on Chrome. Others advise the use of XMLHttpRequests, which seem to have suffered the same fate.
  I have attempted the use of 
  <code>@HostListener('window:onbeforeunload', ['$event'])</code>, and equivalent in the HTML <code>(window:beforeunload)="doBeforeUnload($event)"</code>, but all refuse to cooperate. I can get console.logs to show up, but the API never receives any call to logout the user.
  I have also used <code>navigator.sendBeacon</code> and, despite its function returning true, signalling that the job was sent to the browser queue, nothing ever materializes.</p>
  
  <p>Currently, the logout function is this:</p>
  
  <pre><code>userLogout(): Observable&lt;any&gt; {
      return this.apiService.get('/Account/Logout/');
    }
  </code></pre>
  
  <p>Which, in turn, is a generic http get function:</p>
  
  <pre><code>get&lt;T&gt;(url: string, options?: { params: HttpParams }): Observable&lt;any&gt; {
      return this.httpRequest&lt;T&gt;('get', url, null, options ? options.params : null);
    }
  </code></pre>
  
  <p>The full url is added with the use of an HttpInterceptor. The logout function itself is working, as it is used in a menu option that works as expected when used manually. So the function should not be the problem.</p>
  
  <p>All I'm attempting to do is to call the userLogout function either in a sync or async way and inform the backend that the user has left.</p>