Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Interaction between components using a service

I have two component A and B, where component A contains a button. I wish when user click on this button, fire a function on component B

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

And the component B is rendered using routing.I am considering using a service with an observable boolean that indicate if the button in A is clicked. Is this the right way to achieve it ?

like image 920
LHIOUI Avatar asked Jan 31 '17 13:01

LHIOUI


People also ask

How do you communicate between components of a service?

You have to use a service to communicate between your two components. Your service has a property event. So the component A can emit the event and the component B can subscribe to it. Use RxJS to emit and subscribe to your event.

How do you communicate between components in Angular service?

Angular 10 Message Service With the message service you can subscribe to new messages in any component with onMessage() method, send messages from any component with the sendMessage(message: string) method, and clear messages from any component with the clearMessages() method.

Which component interacts with services in angular 2?

Smart ComponentSmart/parent component is responsible to interact with the server/cloud through the Service.


1 Answers

Shared service is a common way of communication between non-related components. Your components need to use a single instance of the service, so make sure it's provided at the root level.

An example using the BehaviorSubject as a data delegate:

Shared service:

@Injectable()
export class SharedService {

    isVisibleSource: BehaviorSubject<boolean> = new BehaviorSubject(false);

    constructor() { }
}

Component 1:

export class Component1 {

    isVisible = 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(): void {
        this.sharedService.isVisibleSource.subscribe((isVisible) => {
            console.log('isVisible: ', isVisible); // => true/false
        });
    }
}

It is worth mentioning that BehaviorSubject upon a subscription returns the last value it holds, therefore the component from the example above will be updated with the most recent value immediately after the instantiation.

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

this.sharedService.isVisibleSource.getValue(); // => true/false
like image 76
seidme Avatar answered Oct 10 '22 11:10

seidme