title: Angular : passing data between components using service
body: <p>I work on Angular 4, onclick of one of the 'groups' its tile should be added to the list of 'favourites' (which is an array). For this I used <code>BehaviorSubject</code>. I am able to display <code>default message</code> on my <code>FavouriteComponent.html</code> but when I click on newMessage() from <code>GroupComponent.ts</code> the value in <code>FavouriteComponent.html</code> is not changing it remains <code>default message</code>. Please guide me where I went wrong or is there any other way to achieve my requirement.</p>
  
  <p>DataService.ts</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { BehaviorSubject } from 'rxjs/BehaviorSubject';
  @Injectable()
  export class DataService {
  
    private messageSource = new BehaviorSubject("default message");
    currentMessage = this.messageSource.asObservable();
  
    constructor() { }
  
    changeMessage(message: string) {
      this.messageSource.next(message)
    }
  
  }
  </code></pre>
  
  <p>FavouriteComponent.ts</p>
  
  <pre><code>import { DataService } from "../data.service";
  @Component({
    selector: 'app-parent',
    template: `
      {{message}}
    `
  })
  export class FavouriteComponent implements OnInit {
  
    message:string;
  
    constructor(private data: DataService) { }
  
    ngOnInit() {
      this.data.currentMessage.subscribe(message =&gt; this.message = message)
    }
  
  }
  </code></pre>
  
  <p>GroupComponent.ts</p>
  
  <pre><code>import { DataService } from "../data.service";
  @Component({
    selector: 'app-sibling',
    template: `
      {{message}}
      &lt;button (click)="newMessage()"&gt;New Message&lt;/button&gt;
    `,
    styleUrls: ['./sibling.component.css']
  })
  export class GroupComponent implements OnInit {
  
    message:string;
  
    constructor(private data: DataService) { }
  
    ngOnInit() {
      this.data.currentMessage.subscribe(message =&gt; this.message = message)
    }
  
    newMessage() {
      this.data.changeMessage("new title to add")
    }
  
  }
  </code></pre>