Components via <router-exit>

I have a root component with a variable boolean, and I want to subscribe to this boolean change with the component in my <router-outlet> . I understand that I need to use a common bi-directional service. However, documents for shared services just don't make much sense to me. (I think I canโ€™t wrap my head around the example of an astronaut) here , any help would be greatly appreciated, here is some code to show what I'm trying to do.

root component

 @Component({ selector: 'my-app', template: `<nav [state]="boolshow" (show)="changeValue($event)" ></nav> <article><router-outlet></router-outlet></article> <-----component in router here <footer></footer> <h3>toggle state: {{boolshow}}</h3>`, styleUrls: ['./Css/app.css'], }) export class AppComponent { boolshow: boolean; <-----boolean that needs to be read } 
+7
source share
1 answer

This is what they say in Angular2 Docs :

  • Create a service with an observable

  • Introduce the same service in both components

  • From one component you update data to a service

  • From another component, you are reading data from a service

Ref.

Service:

 @Injectable() export class DataService { private dataObs$ = new Subject(); getData() { return this.dataObs$; } updateData(data: boolean) { this.dataObs$.next(data); } } 

Components:

 @Component({ selector: 'my-app', template: `<div (click)="updateData(false)">Click t oupdate Data FALSE</div> <div (click)="updateData(true)">Click to update Data TRUE</div> <child></child> ` }) export class AppComponent { constructor(private dataService: DataService) {} updateData(value: boolean) { this.dataService.updateData(value); } } @Component({ selector: 'child', template: `<div><p>data from Service HERE:</p><p style="color:red"> {{myData}}</p></div>` }) export class ChildComponent { myData: boolean; constructor(private dataService: DataService) {} ngOnInit() { this.dataService.getData().subscribe(data => { this.myData = data; }) } } 

Make sure that the components have the same service (Singleton):

 @NgModule({ imports: [ BrowserModule, HttpModule ], declarations: [ AppComponent, ChildComponent ], providers: [ DataService ], bootstrap: [ AppComponent ] }) 

A full working example can be found HERE : http://plnkr.co/edit/nJVC36y5TIGoXEfTkIp9?p=preview

PS: Since communication through Service works in Angular2, it doesnโ€™t matter if your component is inside the router through the router, it works everywhere.

+14
source

All Articles