title: Reconnecting a websocket in Angular and rxjs?
body: <p>I have a ngrx/store (v2.2.2) and rxjs (v5.1.0)  based application that listens to a web socket for incoming data using an observable. When I start the application I receive incoming data flawlessly.</p>
  
  <p>However after a while (updates are coming in quite infrequently) the connection seem to get lost and I don't get anymore incoming data. My code:</p>
  
  <h2>The service</h2>
  
  <pre><code>import { Injectable, OnInit } from '@angular/core';
  import { Observable } from 'rxjs';
  
  @Injectable()
  export class MemberService implements OnInit {
  
    private websocket: any;
    private destination: string = "wss://notessensei.mybluemix.net/ws/time";
  
    constructor() { }
  
    ngOnInit() { }
  
    listenToTheSocket(): Observable&lt;any&gt; {
  
      this.websocket = new WebSocket(this.destination);
  
      this.websocket.onopen = () =&gt; {
        console.log("WebService Connected to " + this.destination);
      }
  
      return Observable.create(observer =&gt; {
        this.websocket.onmessage = (evt) =&gt; {
          observer.next(evt);
        };
      })
        .map(res =&gt; res.data)
        .share();
    }
  }
  </code></pre>
  
  <h2>The subscriber</h2>
  
  <pre><code>  export class AppComponent implements OnInit {
  
    constructor(/*private store: Store&lt;fromRoot.State&gt;,*/ private memberService: MemberService) {}
  
    ngOnInit() {
      this.memberService.listenToTheSocket().subscribe((result: any) =&gt; {
        try {
          console.log(result);
          // const member: any = JSON.parse(result);
          // this.store.dispatch(new MemberActions.AddMember(member));
        } catch (ex) {
          console.log(JSON.stringify(ex));
        }
      })
    }
  }
  </code></pre>
  
  <p>What do I need to do to reconnect the web socket when it times out, so the observable continues to emit incoming values?</p>
  
  <p>I had a look at some Q&amp;A <a href="https://stackoverflow.com/questions/43328451/rxjs-observable-with-websocket">here</a>, <a href="https://stackoverflow.com/questions/36851347/angular2-websocket-how-to-return-an-observable-for-incoming-websocket-messages">here</a> and <a href="https://stackoverflow.com/questions/36675104/reconnecting-a-websocket-with-a-shared-rxjs-observable">here</a> and it didn't seem to address this question (in a way I could comprehend).</p>
  
  <p>Note: the websocket at <code>wss://notessensei.mybluemix.net/ws/time</code> is live and emits a time stamp once a minute (in case one wants to test that).</p>
  
  <p>Advice is greatly appreciated!</p>