updating variable changes in components from a service with angular2
<p>My app has a NameService which holds the name. </p>

<p>There are two child components of App, Navbar and TheContent which reference this service. Whenever the name changes in the service, i want it to update in both of the other components. How can i do this?</p>

<pre class="lang-ts prettyprint-override"><code>import {Component, Injectable} from 'angular2/core'

// Name Service

@Injectable()
class NameService {
  name: any;
  constructor() {
    this.name = "Jack";
  }
  change(){
    this.name = "Jane";
  }
}

// The navbar
@Component({
  selector: 'navbar',
  template: '&lt;div&gt;This is the navbar, user name is {{name}}.&lt;/div&gt;'
})
export class Navbar {
  name: any;
  constructor(nameService: NameService) {
    this.name = nameService.name;
  }
}

// The content area
@Component({
  selector: 'thecontent',
  template: '&lt;div&gt;This is the content area. Hello user {{name}}. &lt;button (click)=changeMyName()&gt;Change the name&lt;/button&gt;&lt;/div&gt;'
})
export class TheContent {

  name: any;

  constructor(public nameService: NameService) {
    this.name = nameService.name;
  }
  changeMyName() {
       this.nameService.change();
     console.log(this.nameService.name);
  }
}


@Component({
  selector: 'app',
  providers: [NameService],
  directives: [TheContent, Navbar],
  template: '&lt;navbar&gt;&lt;/navbar&gt;&lt;thecontent&gt;&lt;/thecontent&gt;'
})
export class App {
  constructor(public nameService: NameService) {
  }
}
</code></pre>