Angular2 - Interaction between components using a service

I have two components A and B, where component A contains a button. I want the user to click this button, run the function on component B

<A></A> <router-outlet></router-outlet> 

And component B is rendered using routing. I am considering using a service with an observable boolean indicating whether the button is pressed in A. Is this correct?

+3
angular typescript angular2-routing angular2-services
source share
2 answers

Shared service is a common way of communication between unrelated components. Your components must use a single instance of the service , so make sure it is listed at the root level.

Example using BehaviorSubject as a data delegate :

General service:

 @Injectable() export class SharedService { isVisibleSource: BehaviorSubject<boolean> = new BehaviorSubject(false); constructor() { } } 

Component 1:

 export class Component1 { isVisible: boolean = false; constructor(private sharedService: SharedService) { } onClick(): void { this.isVisible = !this.isVisible; this.sharedService.isVisibleSource.next(this.isVisible); } } 

Component 2:

 export class Component2 { constructor(private sharedService: SharedService) { } ngOnInit() { this.sharedService.isVisibleSource.subscribe((isVisible: boolean) => { console.log('isVisible: ', isVisible); // => true/false }); } } 

It is worth noting that BehaviorSubject upon subscription, returns the last value that it has, so the component from the above example will be updated with the most recent value immediately after creating the instance.

BehaviorSubject also allows you to get the most recent value without even subscribing to it:

 this.sharedService.isVisibleSource.getValue(); // => true/false 
+13
source share

Angular Service

You must use the service to communicate between your two components.

See https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

Your service has a property event. Thus, component A can throw an event, and component B can subscribe to it.

Use RxJS to highlight and subscribe to your event.

If my answer does not satisfy you. Please tell me, and I will work it.

+1
source share

All Articles