In Angular, services are commonly used to manage application state. Instead of passing data between components manually, a shared service acts as a central source of truth that any component can read from or update.
The recommended pattern for state management in Angular services:
BehaviorSubject to store the stateObservable
// state.service.ts - Centralized shared state service
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class StateService {
private messageSource = new BehaviorSubject<string>('Default Message');
currentMessage = this.messageSource.asObservable();
changeMessage(message: string) {
this.messageSource.next(message);
}
}
// sender.component.ts - Updates shared state
import { Component } from '@angular/core';
import { StateService } from '../state.service';
@Component({
selector: 'app-sender',
template: '<button (click)="newMessage()">Change Message</button>'
})
export class SenderComponent {
constructor(private stateService: StateService) {}
newMessage() {
this.stateService.changeMessage('Hello from Sender!');
}
}
// receiver.component.ts - Reads shared state
import { Component, OnInit } from '@angular/core';
import { StateService } from '../state.service';
@Component({
selector: 'app-receiver',
template: '<p>Message: {{ message }}</p>'
})
export class ReceiverComponent implements OnInit {
message: string = '';
constructor(private stateService: StateService) {}
ngOnInit() {
this.stateService.currentMessage.subscribe(msg => this.message = msg);
}
}