Data Transfer Without Parent and Child Component

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.

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;
  });
}


Similar Articles