title: Angular 6: variable is undefined in service after calling from other component
body: <p>i have 2 components login and messenger component and  1 service called as chat service which is in login component.</p>
  
  <p>now the problem is that when i call the chatservice from login component and set the value of socket variable, it updates the variable. but after when i call the other method(recievetextMessage()) of chat service from messenger component, the value of socket variable is undefined. The code is below.</p>
  
  <p><strong>chatservice</strong></p>
  
  <pre><code>import { Injectable } from "@angular/core";
  
  import * as io from 'socket.io-client';
  
  import { Observable } from 'rxjs/Observable';
  
  
  Injectable();
  
  export class chatservice {
  
  
  socket:any;  // the variable that i am updating
  test :any;
  constructor() {
  
  }
  
  socketId = () =&gt; {
  
      this.socket = io(''); //updating of variable from login component is here
      console.log(this.socket);
      let observable = new Observable&lt;{ id: any }&gt;(observer =&gt; {
          this.socket.on('socketId', (data) =&gt; {
              observer.next(data);
          });
          return () =&gt; { this.socket.disconnect(); }
      });
  
      return observable;
  }
  
  sendtextmessage(data) {
      this.socket.emit('sendtextMessage', data);
  }
  
  recievetextMessage = () =&gt; { // called from messenger component
      console.log(this.socket); // gives undefined
      console.log(this.test);
      let observable = new Observable(observer =&gt; {
          console.log(this.test);
          console.log(this.socket);
          this.socket.on('recievetextMessage', (data) =&gt; {
              console.log(data);
              observer.next(data);
          });
          return () =&gt; { this.socket.disconnect(); }
      });
  
      return observable;
  }
  }
  </code></pre>