Services, DI & Communication
Angular Component Communication with Services
Components that are not in a parent-child relationship communicate through a shared service. The service holds a BehaviorSubject or a signal, one component writes to it, and any other component reads it.
What is Component Communication with Services in Angular?
Components that are not in a parent-child relationship communicate through a shared service. The service holds a BehaviorSubject or a signal, one component writes to it, and any other component reads it.
Component Communication with Services example
@Injectable({ providedIn: 'root' })
export class FilterService {
private citySubject = new BehaviorSubject<string>('All');
city$ = this.citySubject.asObservable(); // read-only for consumers
setCity(city: string): void {
this.citySubject.next(city);
}
}Two unrelated components using it
// FilterBar writes
onChange(city: string) { this.filters.setCity(city); }
// JobList reads
jobs$ = this.filters.city$.pipe(switchMap(city => this.api.getJobs(city)));BehaviorSubject holds a current value, so a component subscribing later immediately receives the latest city rather than waiting for the next change.
Key points to remember
- Expose the Subject as an Observable with asObservable() so consumers cannot push values.
- BehaviorSubject suits current-value state; Subject suits one-off events.
- A writable signal is the modern alternative and needs no subscription management.
Common mistakes with Component Communication with Services
- Exposing the Subject itself, letting any component call next() and making the data flow untraceable.
- Providing the service at component level, so each component gets its own isolated instance.
Angular Component Communication with Services— Interview Questions & FAQs
How do two sibling components share data in Angular?+
Through a service injected into both. The service holds the value in a BehaviorSubject or signal; one component updates it and the other subscribes or reads the signal.
