November 2, 2023 07:58 by
Peter
Hello, my friend. I am thrilled to present my debut article.
How can we transfer data from one component to another via service?
Create a service file first.
command- ng g s <service_name>
Step 2. To share data on the click of a button.
<button (click)="sendDataToReceiver()">Send Data</button>
Step 3. Import service in the ts file.
private dataService: DataService
Step 4. Method call.
this.yourServicename.sendData("Hello from Sender");
Step 5. Import your service to send data and get Data.
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.
ngOnInit() {
this.serviceName.getData().subscribe(data => {
this.receivedData = data;
});
}