- Behavior Subject is a unique RxJS subject that stores the most recent information and enables component subscription to updates.
- Shared Service: Facilitates communication across sibling components by serving as a central repository for data.
- Subscription: When the data changes, components that have signed up for the service will automatically receive updates.
Shared Service:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class SharedDataService {
private dataSubject = new BehaviorSubject<any>(null); // Initial value is null
data$ = this.dataSubject.asObservable(); // Observable to share data
updateData(data: any) {
this.dataSubject.next(data); // Method to update data
}
}
Component 1 (Sender):
import { Component } from '@angular/core';
import { SharedDataService } from '../shared-data.service';
@Component({
selector: 'app-component1',
template: `
<button (click)="shareData('cmp2')">Go to Comp 2</button>
<button (click)="shareData('cmp3')">Go to Comp 3</button>
`,
})
export class Component1Component {
data = { api: 'https://api.example.com/discounts' }; // Sensitive data
constructor(private sharedService: SharedDataService) {}
shareData(route: string) {
this.sharedService.updateData(this.data); // Update data in the service
}
}
Component 2 (Receiver):
import { Component, OnInit } from '@angular/core';
import { SharedDataService } from '../shared-data.service';
@Component({
selector: 'app-component2',
template: `Data: {{ data | json }}`,
})
export class Component2Component implements OnInit {
data: any;
constructor(private sharedService: SharedDataService) {}
ngOnInit() {
this.sharedService.data$.subscribe((data) => (this.data = data)); // Subscribe to the data
}
}
Routing Setup:
const routes: Routes = [
{ path: 'cmp1', component: Component1Component },
{ path: 'cmp2', component: Component2Component },
{ path: 'cmp3', component: Component3Component },
];