State Management with Services and RxJS
Illustrates how to manage and share state across components using Angular services and observables from RxJS, adhering to unidirectional data flow principles.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
class StateService {
// BehaviorSubject to manage the state
private readonly _state = new BehaviorSubject<any>({ /* initial state */ });
// Exposed observable part of the BehaviorSubject
readonly state$ = this._state.asObservable();
// Method to get current state value
getState() {
return this._state.getValue();
}
// Method to update the state
updateState(newState: any): void {
this._state.next(newState);
}
}
export default StateService;
This Angular service uses RxJS's BehaviorSubject to store and manage state. It provides a method 'updateState' to update the current state, which components can subscribe to through the exposed 'state$' observable.
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import StateService from './state.service';
@Component({
selector: 'app-example-component',
template: `<div>{{ state | json }}</div>`
})
class ExampleComponent implements OnDestroy {
state: any;
private _stateSubscription: Subscription;
constructor(private stateService: StateService) {
// Subscribe to state changes
this._stateSubscription = stateService.state$.subscribe(newState => {
this.state = newState;
});
}
// Unsubscribe to prevent memory leaks
ngOnDestroy() {
this._stateSubscription.unsubscribe();
}
}
export default ExampleComponent;
This Angular component subscribes to the state updates from 'StateService' and assigns it to a local property 'state'. It implements OnDestroy to ensure subscriptions are cleaned up to prevent memory leaks when the component is destroyed.