To share data between components in Angular using services, use the following step:
1. Create a Shared Service
Use a BehaviorSubject or Subject to store and emit data.
Provide methods to update and access the data.
Example:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class DataService {
private dataSubject = new BehaviorSubject<any>(null); // Holds the data
data$ = this.dataSubject.asObservable(); // Observable to subscribe to
updateData(data: any) {
this.dataSubject.next(data); // Update the data
}
}