Back to course

Data Sharing between Components using Services

The Complete Angular Developer: From Zero to Hero

24. Data Sharing between Components using Services

We learned about @Input and @Output for parent-child communication. But what about communication between components that are not directly related (sibling, cousin, or distant components)? Services provide the perfect mechanism for this, leveraging the singleton nature of root-provided services.

The Shared Data Service

We will create a service that holds data and provides methods for components to update or retrieve that data.

typescript // shared-state.service.ts import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' }) export class SharedStateService { private messageSource = 'Initial Message';

getMessage(): string { return this.messageSource; }

updateMessage(newMessage: string): void { this.messageSource = newMessage; } }

1. Component A (The Sender)

typescript // sender.component.ts constructor(private stateService: SharedStateService) { }

sendUpdate(input: string) { this.stateService.updateMessage(input); }

2. Component B (The Receiver)

typescript // receiver.component.ts public currentMessage: string;

constructor(private stateService: SharedStateService) { this.currentMessage = this.stateService.getMessage(); }

// We need a way to detect changes... // In the next lessons, we will use RxJS (Observables) to make this dynamic and reactive. // For now, this component will need to refresh or be checked manually.

Limitation: The above method is not reactive; Component B must actively call getMessage() to fetch the data. The subsequent lessons on RxJS will solve this by allowing services to notify components of changes asynchronously.