Hello friend, I am very happy to share my first Article.
How do we share data from one component to another through service?
Step 1. Create a service file.
Code
command- ng g s <service_name>Step 2. To share data on the click of a button.
Code
<button (click)="sendDataToReceiver()">Send Data</button>Step 3. Import service in the ts file.
C#
private dataService: DataServiceStep 4. Method call.
C#
this.yourServicename.sendData("Hello from Sender");Step 5. Import your service to send data and get Data.
C#
private dataSubject = new Subject<string>();
sendData(data: string) {
this.dataSubject.next(data);
}
getData() {
return this.dataSubject.asObservable();
}Step 6. Finally, get Data from the Service.
Import your service and create a variable.
C#
ngOnInit() {
this.serviceName.getData().subscribe(data => {
this.receivedData = data;
});
}
Join the conversation! Your thoughts help the community grow.