Steps to Transfer Data Between Unrelated Components
1. Create a Shared Service
The shared service acts as a bridge for data communication between the components.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private dataSource = new BehaviorSubject<any>(null); // Initial value is null
currentData = this.dataSource.asObservable(); // Observable for components to subscribe
// Method to update the data
updateData(data: any) {
this.dataSource.next(data);
}
}
2. Provide the Service
Ensure the service is provided in the root module (done by providedIn: 'root' in the service). This makes it a singleton, accessible across the application.
3. Component A (Sender)
This component sends data using the updateData() method of the service.
import { Component } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-sender',
template: `<button (click)="sendData()">Send Data</button>`,
})
export class SenderComponent {
constructor(private dataService: DataService) {}
sendData() {
const data = { message: 'Hello from Sender Component!' };
this.dataService.updateData(data); // Send data to the service
}
}
4. Component B (Receiver)
This component subscribes to the currentData observable to receive updates.
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-receiver',
template: `<p>{{ receivedData?.message }}</p>`,
})
export class ReceiverComponent implements OnInit {
receivedData: any;
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.currentData.subscribe((data) => {
this.receivedData = data; // Update when data changes
});
}
}