title: Angular 4 emitting and subscribing to an event in a shared service
body: <p>I am emitting an event in my main component:</p>
  
  <p>main.component.ts</p>
  
  <pre><code>this.sharedService.cartData.emit(this.data);
  </code></pre>
  
  <p>Here is my sharedService.ts</p>
  
  <pre><code>import { Component, Injectable, EventEmitter } from '@angular/core';
  export class SharedService {
      cartData = new EventEmitter&lt;any&gt;();
  } 
  </code></pre>
  
  <p>In my other (Sub) Component, I want to access this value, but somehow, the subscription does not work:</p>
  
  <p>dashboard.ts</p>
  
  <pre><code>private myData: any;
  
  constructor(private sharedService: SharedService) {
      this.sharedService.cartData.subscribe(
          (data: any) =&gt; myData = data,
          error =&gt; this.errorGettingData = &lt;any&gt;error,
          () =&gt; this.aggregateData(this.myData));
  }
  </code></pre>
  
  <p>Am I missing something? It works fine when I pass the data as an Injectable.
  Emitting the event (in the main component) happens after some REST calls.</p>
  
  <p><strong>Update</strong></p>
  
  <p>So the problem is that the Subcomponent is created after the first emit of the event. I guess in this case it is better to inject the data into the <code>subcompnent</code> directly.</p>