It's exactly how they say in that Angular2 Docs :
Create a Service with an Observable
Inject the same Service in both components
From one component you update the data to the Service
From the other component you read the data from the Service
Ex.
The Service :
@Injectable()
export class DataService {
private dataObs$ = new Subject();
getData() {
return this.dataObs$;
}
updateData(data: boolean) {
this.dataObs$.next(data);
}
}
The 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 to have the same Service injected in the components (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: This is how the communication via Service works in Angular2, it doesn't matter if your component is inside a router-outlet via a router, it works everywhere.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…