What is the proper way of emitting an event through a service. I have read that declaring the EventEmitter
in the service it's not suitable.
I want to achieve the following.
I have 2 ponents inside the root ponent, when I click in the first ponent, I want to know that the first ponent was clicked in the second ponent.
What is the proper way of emitting an event through a service. I have read that declaring the EventEmitter
in the service it's not suitable.
I want to achieve the following.
I have 2 ponents inside the root ponent, when I click in the first ponent, I want to know that the first ponent was clicked in the second ponent.
Share Improve this question edited May 21, 2024 at 17:18 riki 2,3937 gold badges42 silver badges74 bronze badges asked Jun 2, 2019 at 10:33 TiberiusTiberius 2651 gold badge6 silver badges14 bronze badges 1- Any luck with this? I am also in a asituation where I want to emit event from grandchild ponent to parent AngularJS application and I thought service is better way to avoid multilevel handshakes. – guravman Commented May 14, 2020 at 5:18
2 Answers
Reset to default 13There are four possible scenarios in which you can share your data but it depends upon your requirements
Parent to Child: Sharing Data via Input
Child to Parent: Sharing Data via ViewChild
Child to Parent: Sharing Data via Output() and EventEmitter
Unrelated Components: Sharing Data with a Service
When passing data between ponents that lack a direct connection, such as siblings, grandchildren, etc, you should you a shared service. When you have data that should aways been in sync, I find the RxJS BehaviorSubject very useful in this situation.
You can also use a regular RxJS Subject for sharing data via the service, but here’s why I prefer a BehaviorSubject.
It will always return the current value on subscription - there is no need to call onnext It has a getValue() function to extract the last value as raw data. It ensures that the ponent always receives the most recent data. In the service, we create a private BehaviorSubject that will hold the current value of the message. We define a currentMessage variable handle this data stream as an observable that will be used by the ponents. Lastly, we create function that calls next on the BehaviorSubject to change its value.
The parent, child, and sibling ponents all receive the same treatment. We inject the DataService in the constructor, then subscribe to the currentMessage observable and set its value equal to the message variable.
Now if we create a function in any one of these ponents that changes the value of the message. when this function is executed the new data it’s automatically broadcast to all other ponents. Here its a code snippet.
data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService {
private messageSource = new BehaviorSubject('default message');
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message)
}
}
parent.ponent.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
selector: 'app-parent',
template: `
{{message}}
`,
styleUrls: ['./sibling.ponent.css']
})
export class ParentComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message)
}
}
second.ponent.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
selector: 'app-sibling',
template: `
{{message}}
<button (click)="newMessage()">New Message</button>
`,
styleUrls: ['./sibling.ponent.css']
})
export class SiblingComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message)
}
newMessage() {
this.data.changeMessage("Hello from Sibling")
}
}
I used Replaysubject to notify about changes in data that needed to be updated to the gui in gui-ponent when the data provided by the service changes.
- A service makes a ReplaySubject which holds the data that may change.
- All the gui-ponents / other services subscribe to this object in their init function and get later notified about changes in data. => Do what they need to do.
In my case the service has a polling interval and the data held by it may change without any user actions.